WEB Designing Notes
WEB Designing Notes
UNIT 1
Introduction to php:
PHP (Hypertext Preprocessor) is a popular open-source scripting language that is widely used for web
development. It was originally designed for creating dynamic web pages, and has since evolved to
become a powerful server-side scripting language that can be used to build a wide range of web
applications.
PHP was created in 1994 by Rasmus Lerdorf, and it has since been developed and maintained by a large
community of developers around the world. It is a server-side scripting language, which means that PHP
code is executed on the server before the web page is sent to the client's browser. This allows PHP to be
used for a wide range of tasks, including generating dynamic content, processing form data, interacting
with databases, and more.
Some of the key features of PHP include:
Open-source: PHP is a free and open-source programming language, which means that anyone can use,
modify, and distribute it without any licensing fees.
Easy to learn: PHP has a simple and straightforward syntax that is easy to learn, even for beginners. It is
also supported by a large community of developers who provide tutorials, documentation, and other
resources to help new users get started.
Cross-platform: PHP is compatible with a wide range of operating systems and web servers, including
Windows, Linux, Apache, and Nginx.
Integration with databases: PHP has built-in support for many popular databases, including MySQL,
PostgreSQL, and Oracle, making it easy to create dynamic web applications that interact with databases.
Object-oriented programming: PHP supports object-oriented programming (OOP), which allows
developers to write more organized and maintainable code.
Overall, PHP is a versatile and widely used programming language that is well-suited for web
development. Its open-source nature, ease of use, and broad community support have made it a popular
choice for building a wide range of web applications.
Installation of XAMPP and WAMP server for php:
XAMPP and WAMP are two popular software packages that allow developers to create a local web
server environment for testing and developing PHP applications. Here are the steps to install XAMPP
and WAMP server for PHP:
Installing XAMPP:
1. Download the XAMPP package from the Apache Friends website
([Link]
2. Run the XAMPP installer file and follow the installation wizard.
3. Choose the components you want to install. By default, XAMPP installs Apache, MySQL, PHP,
and Perl.
4. Choose the installation directory where you want to install XAMPP.
5. Complete the installation wizard.
6. Once installed, start the XAMPP Control Panel and start the Apache and MySQL services.
7. Open your web browser and type "[Link] in the address bar. This should open the
XAMPP homepage, indicating that XAMPP is installed and running correctly.
Installing WAMP:
1. Download the WAMP server package from the WampServer website
([Link]
2. Run the WAMP server installer file and follow the installation wizard.
3. Choose the installation directory where you want to install WAMP.
1
Subject: Web Development using PHP & MySQL
4. Choose the components you want to install. By default, WAMP installs Apache, MySQL, and
PHP.
5. Complete the installation wizard.
6. Once installed, start the WAMP server by clicking on the WAMP icon in the system tray and
selecting "Start All Services".
7. Open your web browser and type "[Link] in the address bar. This should open the
WAMP homepage, indicating that WAMP is installed and running correctly.
8. Once you have XAMPP or WAMP installed and running, you can start creating PHP
applications and testing them locally before deploying them to a live server.
Benefits of using PHP MYSQL:
There are many benefits of using PHP and MySQL together for web development:
Open-source: Both PHP and MySQL are open-source technologies, which means that they are
free to use and can be easily customized to meet the needs of any project.
Cross-platform compatibility: PHP and MySQL can be used on a wide range of operating
systems, including Windows, Linux, and Mac OS, making it easy to develop applications that
can be used on any platform.
Easy to learn: PHP and MySQL both have a simple and straightforward syntax, making them
easy to learn and use, even for beginners.
Fast and efficient: PHP is a server-side scripting language, which means that it runs on the server
and generates HTML pages that are sent to the client's browser. This makes PHP applications
fast and efficient, as the processing is done on the server.
Database integration: MySQL is a popular open-source relational database management system,
and it integrates seamlessly with PHP, making it easy to build dynamic web applications that
interact with databases.
Scalability: PHP and MySQL are highly scalable, meaning that they can handle large amounts of
data and traffic without slowing down or crashing.
Community support: PHP and MySQL both have large and active developer communities,
providing users with access to a wide range of resources, including tutorials, documentation, and
support forums.
Overall, using PHP and MySQL together provides developers with a powerful and flexible platform for
building dynamic, scalable, and efficient web applications.
Server client environment in PHP:
In a server-client environment for PHP, the server is responsible for running the PHP scripts and
generating HTML pages that are sent to the client's browser. The client's browser then interprets the
HTML and displays the web page to the user.
Here's how the server-client environment for PHP works:
1. The client requests a web page from the server by typing in a URL or clicking on a link.
2. The server receives the request and checks if it corresponds to a PHP script.
3. If the requested page is a PHP script, the server runs the script and generates an HTML page that
is sent back to the client.
4. The client's browser receives the HTML page and interprets it, displaying the web page to the
user.
5. If the web page contains any dynamic content, such as data from a database or user input, the
client sends a request back to the server, and the server generates a new HTML page with the
updated content.
In this server-client environment, the server is responsible for handling the processing and generation of
the HTML pages, while the client's browser is responsible for rendering the pages and handling user
2
Subject: Web Development using PHP & MySQL
interactions. PHP provides a powerful server-side scripting language that allows developers to create
dynamic and interactive web applications that can be deployed on a wide range of server environments.
Web Browser in PHP:
A web browser is a software application that is used to access and view web pages on the internet. It
retrieves information from web servers and displays it on the user's computer or device.
The primary function of a web browser is to provide a user interface for browsing the internet,
displaying web pages, and navigating between them. Web browsers use Hypertext Transfer Protocol
(HTTP) to communicate with web servers and retrieve web pages, and they use Hypertext Markup
Language (HTML) to interpret and display the content of those pages.
Web browsers typically include a variety of features, such as bookmarks or favorites to save frequently
visited web pages, tabbed browsing to allow users to have multiple web pages open at once, and various
options for customizing the browser's appearance and behavior.
Some popular web browsers include Google Chrome, Mozilla Firefox, Microsoft Edge, Safari, and
Opera. Each browser has its own set of features, user interface, and compatibility with web standards
and technologies.
In addition to displaying web pages, modern web browsers can also run web applications, such as email
clients, word processors, and photo editors. Web browsers can also support browser extensions and add-
ons, which can add additional features and functionality to the browser.
PHP is a server-side scripting language, which means that it runs on the server and generates HTML
pages that are sent to the client's browser. The client's browser then interprets the HTML and displays
the web page to the user.
Here are some ways in which PHP interacts with the client's browser:
1. Generating HTML: PHP is used to generate HTML pages dynamically, based on user input or
other factors. The PHP code is processed on the server, and the resulting HTML is sent to the
client's browser for rendering.
2. Handling form submissions: When a user submits a form on a web page, the data is sent to the
server for processing. PHP can be used to handle the form submission, validate the input, and
update the database or generate a response page.
3. Handling cookies and sessions: PHP can be used to manage cookies and sessions, which are used
to store information about the user's preferences and activity on the website.
4. Handling redirects: PHP can be used to handle redirects, which are used to redirect the user to a
different page or URL based on certain conditions.
5. Handling client-side scripting: While PHP is primarily a server-side scripting language, it can
also be used to generate client-side scripts, such as JavaScript, which are executed on the client's
browser.
Overall, PHP plays a crucial role in web development by providing a powerful server-side scripting
language that allows developers to create dynamic, interactive, and responsive web applications that can
be deployed on a wide range of server environments and interact with the client's browser in various
ways.
Web Server Installation & Configuration Files in PHP:
To install and configure a web server for PHP development, you will need to follow a few steps:
1. Choose a web server: There are many web servers available, including Apache, Nginx, and
Microsoft IIS. Apache is one of the most popular web servers and is widely used for PHP
development.
3
Subject: Web Development using PHP & MySQL
2. Install the web server: Once you have chosen a web server, you will need to download and install
it on your computer. Follow the instructions provided by the web server software to complete the
installation.
3. Install PHP: After installing the web server, you will need to install PHP. Download the PHP
software from the official website and follow the installation instructions.
4. Configure PHP with the web server: After installing PHP, you will need to configure it to work
with the web server. This usually involves modifying the web server's configuration file to
include the path to the PHP executable.
5. Test the installation: Once you have completed the installation and configuration, you should test
the setup to ensure that everything is working properly. Create a simple PHP script and place it
in the web server's document root directory. Then, navigate to the script in your web browser and
ensure that it is executed properly.
The configuration files that are used to set up and configure the web server and PHP depend on the
specific software that you are using. For example, if you are using Apache as your web server, the
configuration files are typically located in the /etc/apache2/ directory on Linux or macOS, or in the
C:\Program Files (x86)\Apache Group\Apache2\conf directory on Windows. The specific configuration
files that you will need to modify will vary depending on your setup, but common files include
[Link] for Apache and [Link] for PHP.
OOPs with PHP:
Object-oriented programming (OOP) is a programming paradigm that is used to model complex systems
by representing them as a collection of objects that interact with each other. PHP supports OOP, which
allows developers to write modular, reusable, and scalable code.
Here are some key concepts of OOP in PHP:
1. Classes and Objects: A class is a blueprint for creating objects, and an object is an instance of a
class. In PHP, classes are defined using the class keyword, and objects are created using the new
keyword.
2. Properties: Properties are variables that belong to an object. They can be defined within a class
using the public, private, or protected keywords to control their visibility.
3. Methods: Methods are functions that belong to an object. They can be defined within a class
using the public, private, or protected keywords to control their visibility.
4. Inheritance: Inheritance is a mechanism that allows a class to inherit properties and methods
from another class. In PHP, inheritance is achieved using the extends keyword.
5. Polymorphism: Polymorphism is a concept that allows objects of different classes to be treated
as if they were of the same class. This is achieved in PHP through interfaces and abstract classes.
6. Encapsulation: Encapsulation is the concept of hiding implementation details and exposing only
the necessary information to the outside world. In PHP, this is achieved through access modifiers
such as public, private, and protected.
Using OOP in PHP allows developers to create code that is more modular, maintainable, and scalable. It
also allows for better code reuse, as objects can be easily instantiated and used throughout an
application.
Language basics of PHP:
Here are some of the basic concepts of PHP:
1. Variables: PHP variables are used to store data values, such as numbers or strings. Variables are
declared using the $ symbol, followed by the variable name.
2. Data Types: PHP supports several data types, including integers, floating-point numbers, strings,
and booleans.
4
Subject: Web Development using PHP & MySQL
3. Operators: PHP supports a range of operators, including arithmetic operators (+, -, *, /),
assignment operators (=, +=, -=), comparison operators (==, !=, >, <), and logical operators (&&,
||, !).
4. Conditional Statements: PHP includes conditional statements such as if, else, and switch that
allow for different blocks of code to be executed based on the result of a condition.
5. Loops: PHP includes loop statements such as for, while, and foreach that allow for code to be
executed repeatedly.
6. Functions: PHP functions are used to encapsulate blocks of code that can be reused throughout a
program. Functions are declared using the function keyword.
7. Arrays: PHP arrays are used to store collections of data. Arrays can be indexed using numerical
keys or associative keys.
8. Superglobals: PHP includes several predefined variables, called superglobals, that can be
accessed from anywhere in a program. Some common superglobals include $_GET, $_POST,
$_SERVER, and $_SESSION.
These are just a few of the basic concepts of PHP. PHP also includes a range of built-in functions, as
well as support for object-oriented programming and database integration.
Syntax in php:
The syntax of PHP is similar to other programming languages, but there are a few unique aspects to be
aware of. Here are some key syntax elements of PHP:
1. Statements: PHP statements are typically terminated with a semicolon (;). Statements can be
grouped together using curly braces ({}) to create code blocks.
2. Comments: PHP comments are used to add explanatory text to code without affecting its
functionality. Single-line comments are created using // or #, while multi-line comments are
created using /* and */.
3. Variables: PHP variables are declared using the $ symbol, followed by the variable name.
Variable names can contain letters, numbers, and underscores, but cannot start with a number.
4. Strings: PHP strings are enclosed in quotes (single or double), and can include variables and
special characters using escape sequences (such as \n for a new line).
5. Operators: PHP supports a range of operators, including arithmetic operators (+, -, *, /),
assignment operators (=, +=, -=), comparison operators (==, !=, >, <), and logical operators (&&,
||, !).
6. Functions: PHP functions are declared using the function keyword, followed by the function
name and any parameters. The function block is enclosed in curly braces ({}) and can include
return statements to return values.
7. Control Structures: PHP includes control structures such as if, else, for, while, switch, and
foreach, which allow for different blocks of code to be executed based on conditions or
iterations.
8. Arrays: PHP arrays are created using square brackets ([]), and can include both numerical and
associative keys.
These are just a few of the key syntax elements of PHP. PHP also includes support for object-oriented
programming, database integration, and a range of other advanced features.
Example:
<?php
/*
5
Subject: Web Development using PHP & MySQL
This is a multi-line
comment
*/
$name = "John"; // This declares a variable called $name and assigns it the value "John"
?>
Variable,constants and data type:
Variables, constants, and data types are key concepts in PHP programming. Here is an explanation of
each with an example:
Variables: A variable is a container that holds a value that can be used and changed throughout the
script. In PHP, variables are declared using the $ symbol, followed by the variable name. Here's an
example:
$name = "John";
In this example, we declare a variable called $name and assign it the value "John".
Constants: A constant is a value that cannot be changed throughout the script. In PHP, constants are
declared using the define() function. Here's an example:
define("PI", 3.14);
In this example, we declare a constant called PI and assign it the value 3.14.
Data types: PHP supports several data types, including strings, integers, floats, booleans, arrays, and
objects. Here are examples of each:
// String data type
$name = "John";
Note that PHP is a loosely typed language, which means that variables can change their data type at
runtime based on the value they hold. For example, a variable that initially holds an integer value can be
changed to a string value later in the script.
Expressions and operators:
Expressions and operators are fundamental concepts in PHP programming. An expression is a
combination of variables, constants, functions, and operators that evaluate to a value. An operator is a
symbol that performs a specific operation on one or more values. Here are some examples of
expressions and operators in PHP:
Arithmetic operators: Arithmetic operators perform mathematical operations such as addition,
subtraction, multiplication, and division. Here are some examples:
// Addition operator
$sum = 10 + 5; // $sum equals 15
// Subtraction operator
$diff = 10 - 5; // $diff equals 5
// Multiplication operator
$product = 10 * 5; // $product equals 50
// Division operator
$quotient = 10 / 5; // $quotient equals 2
// Modulus operator
$remainder = 10 % 5; // $remainder equals 0
Comparison operators: Comparison operators compare two values and return a boolean value of true
or false. Here are some examples:
// Equal to operator
$is_equal = 10 == 5; // $is_equal equals false
$is_greater = 10 > 5;
$is_both_true = $is_true && $is_greater; // $is_both_true equals true
// OR operator
$is_false = false;
$is_less = 10 < 5;
$is_either_true = $is_false || $is_less; // $is_either_true equals false
// NOT operator
$is_not_true = !$is_true; // $is_not_true equals false
String operators: String operators perform string concatenation and string length operations. Here are
some examples:
// Concatenation operator
$first_name = "John";
$last_name = "Doe";
$full_name = $first_name . " " . $last_name; // $full_name equals "John Doe"
The if...else statement executes some code if a condition is true and another code if that condition is
false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
Output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:
<?php
$t = date("H");
The switch statement is used to perform different actions based on different conditions.
9
Subject: Web Development using PHP & MySQL
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
PHP Loops
Often when you write code, you want the same block of code to run over and over again a certain
number of times. So, instead of adding several almost equal code-lines in a script, we can use loops.
Loops are used to execute the same block of code again and again, as long as a certain condition is true.
In PHP, we have the following loop types:
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the specified
condition is true
10
Subject: Web Development using PHP & MySQL
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
The PHP do...while Loop
The do...while loop will always execute the block of code once, it will then check the condition, and
repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
Examples
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output,
and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?),
and the loop will continue to run as long as $x is less than, or equal to 5
ExampleGet your own PHP Server
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
The PHP for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:
11
Subject: Web Development using PHP & MySQL
13
Subject: Web Development using PHP & MySQL
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Including html code with php:
You can include HTML code within PHP using the echo statement, which outputs text to the browser.
Here's an example:
<?php
echo "<html>";
echo "<head>";
echo "<title>My Page</title>";
echo "</head>";
echo "<body>";
echo "<h1>Welcome to my page</h1>";
echo "<p>This is some sample text.</p>";
echo "</body>";
echo "</html>";
?>
In this example, the PHP code outputs HTML tags to create a simple web page. The echo statement is
used to output each line of HTML code, enclosed in double quotes.
Alternatively, you can also use the shorthand syntax, called the short_open_tag, to directly include
HTML code within PHP tags. Here's an example:
<?php
// using short open tags
?>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Welcome to my page</h1>
<p>This is some sample text.</p>
</body>
</html>
<?php
// using short open tags
?>
In this example, the HTML code is included directly within the PHP tags. The <?php opening tag is
used to start the PHP code, and the ?> closing tag is used to end it. Between these tags, you can include
HTML code as you would in a regular HTML file
Embedding PHP in Web pages:
To embed PHP code in web pages, you need to save the file with a .php extension instead of .html.
Then you can include PHP code within HTML tags using the PHP opening and closing tags <?php and
?>.
Here's an example:
<!DOCTYPE html>
14
Subject: Web Development using PHP & MySQL
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Welcome to my page</h1>
<p>Today's date is <?php echo date('Y-m-d'); ?></p>
<?php
// More PHP code can go here
?>
</body>
</html>
In this example, the PHP code is embedded within the HTML code using the opening <?php and
closing ?> tags. The echo statement within the PHP code outputs the current date in the Y-m-d format,
which is embedded within the <p> tag in the HTML code.
You can use PHP to dynamically generate HTML content based on data from databases, user input, or
other sources. For example, you can use PHP to create a login form that authenticates users, or to
generate a list of products from an online store. The possibilities are endless!
15
Subject: Web Development using PHP & MySQL
Unit 2
PHP Functions
PHP Built-in Functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to perform
a specific task.
Please check out our PHP reference for a complete overview of the PHP built-in functions.
{
code to be executed;
}
Example
<?php
function writeMsg() {
echo "Hello world!";
}
16
Subject: Web Development using PHP & MySQL
The following example has a function with one argument ($fname). When the familyName()
function is called, we also pass along a name (e.g. Jani), and the name is used inside the function,
which outputs several different first names, but an equal last name:
Example
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Get a Date
The required format parameter of the date() function specifies how to format the date (or time).
Here are some characters that are commonly used for dates:
d - Represents the day of the month (01 to 31)
m - Represents a month (01 to 12)
Y - Represents a year (in four digits)
l (lowercase 'L') - Represents the day of the week
Other characters, like"/", ".", or "-" can also be inserted between the characters to add additional
formatting.
18
Subject: Web Development using PHP & MySQL
Example
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
Get a Time
Here are some characters that are commonly used for times:
H - 24-hour format of an hour (00 to 23)
h - 12-hour format of an hour with leading zeros (01 to 12)
i - Minutes with leading zeros (00 to 59)
This function will work from PHP Version greater than 5.1.2.
Example
To generate hash value using md5 Algorithm −
<?php
19
Subject: Web Development using PHP & MySQL
// send email
mail("someone@[Link]","My subject",$msg);
?>
20
Subject: Web Development using PHP & MySQL
directory functions
String Function
strtolower(); -> converts all characters of the string to lower case
strtoupper(); -> converts all characters of the string to upper case
ucfirst(); -> converts first letter to upper case
substr(int,int) -> prints a string from defined initial character number to defined last number
strpos() -> finds position of the string
Numeric Function
abs() -> returns positive value of a number
sqrt() -> returns square root of a number
round() -> rounds a floating number
array_search() -> searches for a defined value in an array and returns the key for that value
array_reverse() -> returns an array in reverse order
array_keys() -> returns all the keys from an array
Directory Functions
22
Subject: Web Development using PHP & MySQL
23
Subject: Web Development using PHP & MySQL
<?php
echo strlen("Hello world!"); // outputs 12
?>
str_word_count() - Count Words in a String
The PHP str_word_count() function counts the number of words in a string.
ExampleGet your own PHP Server
Count the number of word in the string "Hello world!":
<?php
echo str_word_count("Hello world!"); // outputs 2
?> strrev() - Reverse a String
The PHP strrev() function reverses a string.
ExampleGet your own PHP Server
Reverse the string "Hello world!":
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
24
Subject: Web Development using PHP & MySQL
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
PHP strcmp() Function
ExampleGet your own PHP Server
Compare two strings (case-sensitive):
<?php
echo strcmp("Hello world!","Hello world!");
?>
Special characters in HTML are represented by entities such as & and <. There are two
PHP functions that turn special characters in a string into their entities: one for removing HTML
tags, and one for extracting only meta tags.
Entity-quoting all special characters
The htmlentities() function changes all characters with HTML entity equivalents into those
equivalents (with the exception of the space character). This includes the less-than sign (<), the
greater-than sign (>), the ampersand (&), and accented characters.
For example:
$string = htmlentities("Einstürzende Neubauten");
echo $string;
The htmlspecialchars() function converts the smallest set of entities possible to generate valid
HTML. The following entities are converted:
Ampersands (&) are converted to &
Double quotes (") are converted to "
Single quotes (') are converted to ' (if ENT_QUOTES is on, as described
for htmlentities())
25
Subject: Web Development using PHP & MySQL
$table = get_html_translation_table(HTML_ENTITIES);
$revTrans = array_flip($table);
Einstürzende Neubauten
You can, of course, also fetch the translation table, add whatever other translations you want to
it, and then do the strtr(). For example, if you wanted htmlentities() to also encode spaces
to s, you would do:
$table = get_html_translation_table(HTML_ENTITIES);
$table[' '] = ' ';
26
Subject: Web Development using PHP & MySQL
27
Subject: Web Development using PHP & MySQL
[Link]
The rawurldecode() function decodes URL-encoded strings:
$encoded = 'Programming%20PHP';
echo rawurldecode($encoded);
Programming PHP
Query-string encoding
The urlencode() and urldecode() functions differ from their raw counterparts only in that they
encode spaces as plus signs (+) instead of as the sequence %20. This is the format for building
query strings and cookie values. These functions can be useful in supplying form-like URLs in
the HTML. PHP automatically decodes query strings and cookie values, so you don’t need to use
these functions to process those values. The functions are useful for generating query strings:
$baseUrl = '[Link]
$query = 'PHP sessions -cookies';
echo $url;
[Link]
SQL
Most database systems require that string literals in your SQL queries be escaped. SQL’s
encoding scheme is pretty simple—single quotes, double quotes, NUL-bytes, and backslashes
need to be preceded by a backslash. The addslashes() function adds these slashes, and
the stripslashes() function removes them:
$string = <<< EOF
"It's never going to work," she cried,
as she hit the backslash (\) key.
EOF;
$string = addslashes($string);
echo $string;
echo stripslashes($string);
The delimiter can be any character that is not a letter, number, backslash or space. The most
common delimiter is the forward slash (/), but when your pattern contains forward slashes it is
convenient to choose other delimiters such as # or ~.
Regular Expression Functions
PHP provides a variety of functions that allow you to use regular expressions.
The preg_match(), preg_match_all() and preg_replace() functions are some of the most
commonly used ones:
Function Description
preg_match() Returns 1 if the pattern was found in the string and 0 if not
preg_match_all() Returns the number of times the pattern was found in the string, which may also be 0
preg_replace() Returns a new string where matched patterns have been replaced with another string
Using preg_match()
The preg_match() function will tell you whether a string contains matches of a pattern.
ExampleGet your own PHP Server
Use a regular expression to do a case-insensitive search for "w3schools" in a string:
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str); // Outputs 1
?>
Using preg_match_all()
The preg_match_all() function will tell you how many matches were found for a pattern in a
string.
Example
Use a regular expression to do a case-insensitive count of the number of occurrences of "ain" in a
string:
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // Outputs 4
?>
30
Subject: Web Development using PHP & MySQL
Expression Description
[abc] Find one character from the options between the brackets
Metacharacters
Metacharacters are characters with a special meaning:
Metacharacter Description
| Find a match for any one of the patterns separated by | as in: cat|dog|fish
\d Find a digit
\b Find a match at the beginning of a word like this: \bWORD, or at the end of a word
like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx
Quantifiers
Quantifiers define quantities:
Quantifier Description
31
Subject: Web Development using PHP & MySQL
32
Subject: Web Development using PHP & MySQL
Unit 3
PHP Global Variables - Superglobals
Superglobals were introduced in PHP 4.1.0, and are built-in variables that are always available in
all scopes.
PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables from
anywhere in the PHP script (also from within functions or methods).
PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name
of the variable.
The example below shows how to use the super global variable $GLOBALS:
Example
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
PHP Superglobal - $_SERVER
Super global variables are built-in variables that are always available in all scopes.
PHP $_SERVER
33
Subject: Web Development using PHP & MySQL
$_SERVER is a PHP super global variable which holds information about headers, paths, and
script locations.
The example below shows how to use some of the elements in $_SERVER:
Example
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
The following table lists the most important elements that can go inside $_SERVER:
Element/Code Description
$_SERVER['PHP_SELF'] Returns the filename of the currently executing script
$_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common Gateway Interface (CGI)
the server is using
$_SERVER['SERVER_ADDR'] Returns the IP address of the host server
$_SERVER['SERVER_NAME'] Returns the name of the host server (such as
[Link])
$_SERVER['SERVER_SOFTWARE'] Returns the server identification string (such as
Apache/2.2.24)
$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the information protocol
(such as HTTP/1.1)
$_SERVER['REQUEST_METHOD'] Returns the request method used to access the page (such as
POST)
$_SERVER['REQUEST_TIME'] Returns the timestamp of the start of the request (such as
1377687496)
$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a query
string
$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request
$_SERVER['HTTP_ACCEPT_CHARSET'] Returns the Accept_Charset header from the current request
(such as utf-8,ISO-8859-1)
34
Subject: Web Development using PHP & MySQL
PHP $_REQUEST
PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting
an HTML form.
The example below shows a form with an input field and a submit button. When a user submits
the data by clicking on "Submit", the form data is sent to the file specified in the action attribute
of the <form> tag. In this example, we point to this file itself for processing form data. If you
wish to use another PHP file to process form data, replace that with the filename of your choice.
Then, we can use the super global variable $_REQUEST to collect the value of the input field:
Example
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
PHP $_POST
PHP $_POST is a PHP super global variable which is used to collect form data after submitting
an HTML form with method="post". $_POST is also widely used to pass variables.
The example below shows a form with an input field and a submit button. When a user submits
the data by clicking on "Submit", the form data is sent to the file specified in the action attribute
of the <form> tag. In this example, we point to the file itself for processing form data. If you
wish to use another PHP file to process form data, replace that with the filename of your choice.
Then, we can use the super global variable $_POST to collect the value of the input field:
Example
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
36
Subject: Web Development using PHP & MySQL
</body>
</html>
PHP $_GET
PHP $_GET is a PHP super global variable which is used to collect form data after submitting an
HTML form with method="get".
$_GET can also collect data sent in the URL.
Assume we have an HTML page that contains a hyperlink with parameters:
<html>
<body>
</body>
</html>
When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to
"test_get.php", and you can then access their values in "test_get.php" with $_GET.
The example below shows the code in "test_get.php":
Example
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>
PHP $_FILES:
The global predefined variable $_FILES is an associative array containing items uploaded via
HTTP POST method. Uploading a file requires HTTP POST method form with enctype attribute
set to multipart/form-data.
$HTTP_POST_FILES also contains the same information, but is not a superglobal, and now
been deprecated
The _FILES array contains following properties −
$_FILES['file']['name'] - The original name of the file to be uploaded.
$_FILES['file']['type'] - The mime type of the file.
$_FILES['file']['size'] - The size, in bytes, of the uploaded file.
$_FILES['file']['tmp_name'] - The temporary filename of the file in which the uploaded file
was stored on the server.
$_FILES['file']['error'] - The error code associated with this file upload.
Following [Link] contains a HTML form whose enctype is set to multiform/form-data. It also
has an input file element which presents a button on the form for the user to select file to be
uploaded.
<form action="[Link]" method="POST" enctype="multipart/form-data">
37
Subject: Web Development using PHP & MySQL
38
Subject: Web Development using PHP & MySQL
39
Subject: Web Development using PHP & MySQL
40
Subject: Web Development using PHP & MySQL
Now, we can check each $_POST variable with the test_input() function, and the script looks
like this:
Example:
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
PHP Output Control Functions
PHP Output Control Functions
PHP provides a set of functions that control what content is sent to the browser and when. This is
referred to as output control.
echo, print, printf, print_r... and other similar functions and statements
Notices, warnings and errors from PHP
Any content outside of the <?php ?> tags
PHP and the backend on which it is running may hold the output in a buffer before sending it to
the user.
Note: The output control functions can create any number of output buffers. Output buffers catch
output given by the program. Each new output buffer is placed on the top of a stack of output
buffers, and any output it provides will be caught by the buffer below it. The output control
functions handle only the topmost buffer, so the topmost buffer must be removed in order to
control the buffers below it.
Installation
The PHP output control functions are part of the PHP core. No installation is required to use
these functions.
Runtime Configuration
41
Subject: Web Development using PHP & MySQL
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
PHP Sessions
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.
42
Subject: Web Development using PHP & MySQL
and when you end. But on the internet there is one problem: the web server does not know who
you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple pages
(e.g. username, favorite color, etc). By default, session variables last until the user closes the
browser.
So; Session variables hold information about one single user, and are available to all pages in
one application.
Start a PHP Session
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP
session and set some session variables:
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
<?php
43
Subject: Web Development using PHP & MySQL
</body>
</html>
Another way to show all the session variable values for a user session is to run the following
code:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
PHP File Handling
File handling is an important part of any web application. You often need to open and process a
file for different tasks.
Example
<?php
echo readfile("[Link]");
?>
PHP File Open/Read/Close
PHP Open File - fopen()
A better method to open files is with the fopen() function. This function gives you more options
than the readfile() function.
We will use the text file, "[Link]", during the lessons:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
The first parameter of fopen() contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened. The following example also
generates a message if the fopen() function is unable to open the specified file:
ExampleGet your own PHP Server
<?php
$myfile = fopen("[Link]", "r") or die("Unable to open file!");
echo fread($myfile,filesize("[Link]"));
fclose($myfile);
?>
Tip: The fread() and the fclose() functions will be explained below.
The file may be opened in one of the following modes:
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at
the end of the file. Creates a new file if the file doesn't exist
45
Subject: Web Development using PHP & MySQL
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at
the end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
</body>
</html>
PHP Download File
PHP enables you to download file easily using built-in readfile() function. The readfile() function
reads a file and writes it to the output buffer.
46
Subject: Web Development using PHP & MySQL
47
Subject: Web Development using PHP & MySQL
UNIT 4
MySQL - Introduction
What is a Database?
A database is a separate application that stores a collection of data. Each database has one or
more distinct APIs for creating, accessing, managing, searching and replicating the data it holds.
Other kinds of data stores can also be used, such as files on the file system or large hash tables in
memory but data fetching and writing would not be so fast and easy with those type of systems.
Nowadays, we use relational database management systems (RDBMS) to store and manage huge
volume of data. This is called relational database because all the data is stored into different
tables and relations are established using primary keys or other keys known as Foreign Keys.
A Relational DataBase Management System (RDBMS) is a software that −
Enables you to implement a database with tables, columns and indexes.
Guarantees the Referential Integrity between rows of various tables.
Updates the indexes automatically.
Interprets an SQL query and combines information from various tables.
RDBMS Terminology
Before we proceed to explain the MySQL database system, let us revise a few definitions related
to the database.
Database − A database is a collection of tables, with related data.
Table − A table is a matrix with data. A table in a database looks like a simple spreadsheet.
Column − One column (data element) contains data of one and the same kind, for example the
column postcode.
Row − A row (= tuple, entry or record) is a group of related data, for example the data of one
subscription.
Redundancy − Storing data twice, redundantly to make the system faster.
Primary Key − A primary key is unique. A key value can not occur twice in one table. With a
key, you can only find one row.
Foreign Key − A foreign key is the linking pin between two tables.
Compound Key − A compound key (composite key) is a key that consists of multiple columns,
because one column is not sufficiently unique.
Index − An index in a database resembles an index at the back of a book.
Referential Integrity − Referential Integrity makes sure that a foreign key value always points to
an existing row.
MySQL Database
MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL is
developed, marketed and supported by MySQL AB, which is a Swedish company. MySQL is
becoming so popular because of many good reasons −
MySQL is released under an open-source license. So you have nothing to pay to use it.
MySQL is a very powerful program in its own right. It handles a large subset of the functionality
of the most expensive and powerful database packages.
MySQL uses a standard form of the well-known SQL data language.
MySQL works on many operating systems and with many languages including PHP, PERL, C,
C++, JAVA, etc.
MySQL works very quickly and works well even with large data sets.
MySQL is very friendly to PHP, the most appreciated language for web development.
48
Subject: Web Development using PHP & MySQL
MySQL supports large databases, up to 50 million rows or more in a table. The default file size
limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a
theoretical limit of 8 million terabytes (TB).
MySQL is customizable. The open-source GPL license allows programmers to modify the
MySQL software to fit their own specific environments.
Introduction to SQL
What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in 1987
What Can SQL do?
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and views
49
Subject: Web Development using PHP & MySQL
Every table is broken up into smaller entities called fields. The fields in the Customers table
consist of CustomerID, CustomerName, ContactName, Address, City, PostalCode and Country.
A field is a column in a table that is designed to maintain specific information about every record
in the table.
A record, also called a row, is each individual entry that exists in a table. For example, there are
91 records in the above Customers table. A record is a horizontal entity in a table.
A column is a vertical entity in a table that contains all information associated with a specific
field in a table.
phpMyAdmin
phpMyAdmin is an open-source software tool introduced on September 9, 1998, which is
written in PHP. Basically, it is a third-party tool to manage the tables and data inside the
database. phpMyAdmin supports various type of operations on MariaDB and MySQL. The
main purpose of phpMyAdmin is to handle the administration of MySQL over the web.
It is the most popular application for MySQL database management. We can create, update,
drop, alter, delete, import, and export MySQL database tables by using this software.
phpMyAdmin also supports a wide range of operation like managing databases, relations,
tables, columns, indexes, permissions, and users, etc., on MySQL and MariaDB. These
operations can be performed via user interface, while we still have the ability to execute any
SQL statement.
phpMyAdmin is translated into 72 languages and also supports both RTL and LTR
languages so that the wide range of people can easily use this software. We can run MySQL
queries, repair, optimized, check tables, and also execute other database management commands.
phpMyAdmin can also be used to perform administrative tasks such as database creation,
query execution.
phpMyAdmin is a GUI-based application which is used to manage MySQL database. We can
manually create database and table and execute the query on them. It provides a web-based
interface and can run on any server. Since it is web-based, so we can access it from any
computer.
Features of phpMyAdmin
phpMyAdmin supports several features that are given below:
phpMyAdmin can create, alter, browse, and drop databases, views, tables, columns, and indexes.
It can display multiple results sets through queries and stored procedures.
phpMyAdmin use stored procedure and queries to display multiple results sets.
It supports foreign keys and InnoDB tables.
phpMyAdmin can track the changes done on databases, views, and tables.
We can also create PDF graphics of our database layout.
phpMyAdmin can be exported into various formats such as XML, CSV, PDF, ISO/IEC 26300 -
OpenDocument Text and Spreadsheet.
It supports mysqli, which is the improved MySQL extension.
phpMyAdmin can interact with 80 different languages.
phpMyAdmin can edit, execute, and bookmark any SQL-statements and even batch-queries.
By using a set of pre-defined functions, it can transform stored data into any format. For
example - BLOB-data as image or download-link.
It provides the facility to backup the database into different forms.
Advantage of phpMyAdmin
phpMyAdmin can run on any server or any OS as it has a web browser.
50
Subject: Web Development using PHP & MySQL
We can easily create, delete, and edit the database and can manage all elements using
the graphical interface of phpMyAdmin, which is much easier than MySQL command-line
editor.
phpMyAdmin helps us to control the user's permission and operate several servers at the same
time.
We can also backup our database and export the data into different formats like XML, CSV,
SQL, PDF, OpenDocument Text, Excel, Word, and Spreadsheet, etc.
We can execute complex SQL statements and queries, create and edit functions, triggers, and
events using the graphical interface of phpMyAdmin.
Disadvantage of phpMyAdmin
phpMyAdmin is a simple interface, but quite tough for a beginner to learn.
phpMyAdmin is difficult to install as it needs three more software tools before installation,
which is- Apache server, PHP, and MySQL.
We have to install all these software tools individually, whereas XAMPP already contains them
in a single package. XAMPP is the easiest way to get phpMyAdmin.
It has no schema visualization.
phpMyAdmin is a web-based software tool which runs only on the browser, so It completely
depends on browsers.
It does not have auto-compilation capability.
Data Backup problem with phpMyAdmin
phpMyAdmin lacks a lot of features in import/export functionality. There are some backup
problems with phpMyAdmin that are given below:
Scheduling - There is no way to export the data of the database in phpMyAdmin automatically.
Storage media support - As we have discussed earlier, phpMyAdmin is web-based software, so
it runs only on the browser. We can take backups only to local drives of our system.
Compression, Encryption, and other option - The files which are exported with phpMyAdmin
are saved as common text files, with any additional processing. Whereas storing these files in the
original form usually takes a lot of disk storage.
Create a New Database in phpMyAdmin
We have seen many apps uses any specific backend database or services which are used to
store data of the app within itself. In this article we will take a look on creating a new SQL
database in phpMyAdmin so that we can perform CRUD operations using that database.
In this article we will be simply setting our SQL database in which we will be performing
CRUD operations through our Android Applications. For this, we will be creating a database
using XAMPP on localhost.
Prerequisites : You should be having XAMPP installed on your system so that we can open
phpMyAdmin and run it on local server.
Step 1 : Start your XAMPP server as shown in below screen
For starting your server on Xampp, we simply have to start the services in the Xampp console
which is shown on below screenshot.
51
Subject: Web Development using PHP & MySQL
After starting this services type localhost in your search bar and a page will open. On this page
click on phpMyAdmin option .
Step 2 : Creating a new database
Click on New option which is shown in below screen. After that we have to enter our database
name and then click on Create option to create a new database.
After creating a new database we have to move forward for creating a new SQL table.
Step 3 : Creating a new table for storing our data
After creating your database, see below screen. In this screen we will be creating a new table.
For creating a new table specify your table name and number of columns. In our case we are
specifying our table name as courseDb and specify the number of columns as 4. The 4 different
columns are as follows. The 1st column is for id, 2nd column is for courseName, 3rd column is
for courseDescription and 4th column is for courseDuration.
After clicking on Go option your table will be created. Now we have to add column heading
for our SQLite table. For adding this column heading you will get to see below screen.
Steps to Create the SQL table :
Enter the name for your columns in name section which is shown in above screen.
After that enter the datatype of the data which we will be adding in our database. In this we are
specifying INT for our ID as our ID will be an integer. And in SQL table VARCHAR is used
for storing strings.
In the length/ values section we have to specify the maximum length of the data which we will
be adding in our table. We will not be specifying length for our ID because it is added
automatically.
After that we have to auto increment our ID. For this we have to check the box which is shown
in above screenshot so that it will be incremented automatically on adding new data.
Now our database has been created successfully.
52
Subject: Web Development using PHP & MySQL
Once you are in the phpMyAdmin tool, find and click on the database name that contains the
table you want to drop.
After clicking the database name, the tables will be listed in the right hand panel. Locate the
table you want to drop and select the Drop link.
You will receive a popup. Click the OK button to confirm the delete.
You will receive a deletion success message and see your table disappear from the list. Below is
a quick before and after shot of the table list for a successful deletion.
Loading Data Into a Mysql Table With using phpMyAdmin
you can load data into a table in phpMyAdmin using the graphical user interface (GUI):
Open phpMyAdmin and select the database you want to work with.
53
Subject: Web Development using PHP & MySQL
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Code lines to explain from the example above:
First, we set up an SQL query that selects the id, firstname and lastname columns from the
MyGuests table. The next line of code runs the query and puts the resulting data into a variable
called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into an
associative array that we can loop through. The while() loop loops through the result set and
outputs the data from the id, firstname and lastname columns.
Sorting/Select and Order Data From a MySQL Database
The ORDER BY clause is used to sort the result-set in ascending or descending order.
55
Subject: Web Development using PHP & MySQL
The ORDER BY clause sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
Select and Order Data With MySQLi
The following example selects the id, firstname and lastname columns from the MyGuests table.
The records will be ordered by the lastname column:
Example (MySQLi Object-oriented)Get your own PHP Server
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Code lines to explain from the example above:
First, we set up the SQL query that selects the id, firstname and lastname columns from the
MyGuests table. The records will be ordered by the lastname column. The next line of code runs
the query and puts the resulting data into a variable called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into an
associative array that we can loop through. The while() loop loops through the result set and
outputs the data from the id, firstname and lastname columns.
56
Subject: Web Development using PHP & MySQL
UNIT 5
PHP MySQL Database
What is MySQL?
MySQL is a database system used on the web
MySQL is a database system that runs on a server
MySQL is ideal for both small and large applications
MySQL is very fast, reliable, and easy to use
MySQL uses standard SQL
MySQL compiles on a number of platforms
MySQL is free to download and use
MySQL is developed, distributed, and supported by Oracle Corporation
MySQL is named after co-founder Monty Widenius's daughter: My
The data in a MySQL database are stored in tables. A table is a collection of related data, and it
consists of columns and rows.
Databases are useful for storing information categorically. A company may have a database with
the following tables:
Employees
Products
Customers
Orders
PHP Connect to MySQL
PHP 5 and later can work with a MySQL database using:
MySQLi extension (the "i" stands for improved)
PDO (PHP Data Objects)
Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in
2012.
57
Subject: Web Development using PHP & MySQL
MySQLi Installation
For Linux and Windows: The MySQLi extension is automatically installed in most cases, when
php5 mysql package is installed
Open a Connection to MySQL
Before we can access data in the MySQL database, we need to be able to connect to the server:
Example (MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Example (PDO)
58
Subject: Web Development using PHP & MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Note: In the PDO example above we have also specified a database (myDB). PDO require a
valid database to connect to. If no database is specified, an exception is thrown.
Tip: A great benefit of PDO is that it has an exception class to handle any problems that may
occur in our database queries. If an exception is thrown within the try{ } block, the script stops
executing and flows directly to the first catch(){ } block.
MySQLi Procedural:
mysqli_close($conn);
PDO:
$conn = null;
Note: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP with default
update of current_timesamp (like the "reg_date" column), it is no need to be specified in the SQL
query; MySQL will automatically add the value.
The following examples add a new record to the "MyGuests" table:
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
PHP MySQL Select Data
Select Data From a MySQL Database
The SELECT statement is used to select data from one or more tables:
SELECT column_name(s) FROM table_name
or we can use the * character to select ALL columns from a table:
SELECT * FROM table_name
60
Subject: Web Development using PHP & MySQL
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Code lines to explain from the example above:
First, we set up an SQL query that selects the id, firstname and lastname columns from the
MyGuests table. The next line of code runs the query and puts the resulting data into a variable
called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into an
associative array that we can loop through. The while() loop loops through the result set and
outputs the data from the id, firstname and lastname columns.
The following example shows the same as the example above, in the MySQLi procedural way:
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
61
Subject: Web Development using PHP & MySQL
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
62
Subject: Web Development using PHP & MySQL
$conn->close();
?>
PHP MySQL Update Data
Update Data In a MySQL Table Using MySQLi and PDO
The UPDATE statement is used to update existing records in a table:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
Let's look at the "MyGuests" table:
id firstname lastname email reg_date
1 John Doe john@[Link] 2014-10-22 14:26:15
2 Mary Moe mary@[Link] 2014-10-23 10:22:30
The following examples update the record with id=2 in the "MyGuests" table:
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
63
Subject: Web Development using PHP & MySQL
$conn->close();
?>
64