Web Design Using PHP Language PDF
Web Design Using PHP Language PDF
T. Ahmed Abbas
1
PHP
What You Should Already Know?
Before you continue you should have a basic understanding of the following:
HTML
CSS
JavaScript
What is PHP?
PHP is an acronym for "PHP: Hypertext Preprocessor"
PHP is a widely-used, open source scripting language
PHP scripts are executed on the server
PHP is free to download and use
2
What Can PHP Do?
PHP can generate dynamic page content
PHP can create, open, read, write, delete, and close files on the server
PHP can collect form data
PHP can send and receive cookies
PHP can add, delete, modify data in your database
PHP can be used to control user-access
PHP can encrypt data
With PHP you are not limited to output HTML. You can output images, PDF files,
and even Flash movies. You can also output any text, such as XHTML and XML.
Why PHP?
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP supports a wide range of databases
PHP is free. Download it from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side
PHP Support
If your server has activated support for PHP you do not need to do anything.
Just create some .php files, place them in your web directory, and the server
will automatically parse them for you.
OR
3
A PHP script is executed on the server, and the plain HTML result is sent
back to the browser.
<?php
// PHP code goes here
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a
built-in PHP function "echo" to output the text "Hello World!" on a web page:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Outputs
4
Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
Outputs
Hello world!
5
10.5
After the execution of the statements above, the variable $txt will hold the
value Hello world!, the variable $x will hold the value 5, and the
variable $y will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring
a variable. It is created the moment you first assign a value to it.
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different
variables)
Output Variables
The PHP echo statement is often used to output data to the screen.
5
The following example will show how to output text and a variable:
Example
<?php
$txt = "My University ";
echo "I love $txt!";
?>
Outputs
I love My University!
The following example will produce the same output as the example above:
Example
<?php
$txt = " My University ";
echo "I love " . $txt . "!";
?>
Outputs
I love My University!
Example
<?php
$x = 5; $y = 4;
echo $x + $y;
?>
Outputs 9
6
PHP automatically converts the variable to the correct data type, depending on
its value.
In other languages such as C, C++, and Java, the programmer must declare
the name and type of the variable before using it.
The scope of a variable is the part of the script where the variable can be
referenced/used.
local
global
static
Example
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
7
Example
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>"; }
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
Outputs
You can have local variables with the same name in different functions, because
local variables are only recognized by the function in which they are declared.
To do this, use the global keyword before the variables (inside the function):
Example
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y; }
myTest();
echo $y; // outputs 15
?>
Example
8
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
To do this, use the static keyword when you first declare the variable:
Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Outputs
0
1
2
Then, each time the function is called, that variable will still have the
information it contained from the last time the function was called.
In PHP there are two basic ways to get output: echo and print.
9
In this tutorial we use echo (and print) in almost every example. So, this
chapter contains a little more info about those two output statements.
The differences are small: echo has no return value while print has a return
value of 1 so it can be used in expressions. echo can take multiple parameters
(although such usage is rare) while print can take one argument. echo is
marginally faster than print.
Display Text
The following example shows how to output text with the echo command
(notice that the text can contain HTML markup):
Example
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
Outputs
PHP is Fun!
Hello world!
I'm about to learn PHP!
This string was made with multiple parameters.
Display Variables
11
The following example shows how to output text and variables with
the echo statement:
Example
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
echo "<h2>" . $txt1 . "</h2>";
echo "Study PHP at " . $txt2 . "<br>";
echo $x + $y;
?>
Outputs
Learn PHP
Study PHP at W3Schools.com
9
Display Text
The following example shows how to output text with the print command
(notice that the text can contain HTML markup):
Example
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
Outputs
PHP is Fun!
11
Hello world!
I'm about to learn PHP!
Display Variables
The following example shows how to output text and variables with
the print statement:
Example
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
Outputs
Learn PHP
Study PHP at W3Schools.com
9
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
12
Resource
PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
Example
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
Outputs
Hello world!
Hello world!
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
13
Example
<?php
$x = 5985;
var_dump($x);
?>
Outputs
int(5985)
PHP Float
A float (floating point number) is a number with a decimal point or a number in
exponential form.
In the following example $x is a float. The PHP var_dump() function returns the
data type and value:
Example
<?php
$x = 10.365;
var_dump($x);
?>
Outputs
float(10.365)
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing. You will learn more about
conditional testing in a later chapter of this tutorial.
PHP Array
An array stores multiple values in one single variable.
14
In the following example $cars is an array. The PHP var_dump() function
returns the data type and value:
Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
Outputs
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
You will learn a lot more about arrays in later chapters of this tutorial.
PHP Object
An object is a data type which stores data and information on how to process
that data.
First we must declare a class of object. For this, we use the class keyword. A
class is a structure that can contain properties and methods:
Example
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
Outputs
VW
15
PHP NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Example
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Outputs
NULL
PHP Resource
The special resource type is not an actual data type. It is the storing of a
reference to functions and resources external to PHP.
We will not talk about the resource type here, since it is an advanced topic.
16
The example below returns the length of the string "Hello world!":
Example
<?php
echo strlen("Hello world!"); // outputs 12
?>
Example
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
Reverse a String
The PHP strrev() function reverses a string:
Example
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
If a match is found, the function returns the character position of the first
match. If no match is found, it will return FALSE.
The example below searches for the text "world" in the string "Hello world!":
Example
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
17
The output of the code above will be: 6.
Example
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
PHP Constants
A constant is an identifier (name) for a simple value. The value cannot be
changed during the script.
A valid constant name starts with a letter or underscore (no $ sign before the
constant name).
Note: Unlike variables, constants are automatically global across the entire
script.
Syntax
define(name, value, case-insensitive)
18
Parameters:
Example
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
Example
<?php
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
?>
Example
<?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();
?>
PHP Operators
19
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
If $x=10,$y=6;
+ Addition $x + $y Sum of $x 16
and $y
- Subtraction $x - $y Difference 4
of $x and
$y
* Multiplication $x * $y Product of 60
$x and $y
21
% Modulus $x % $y Remainder 4
of $x
divided by
$y
The basic assignment operator in PHP is "=". It means that the left operand
gets set to the value of the assignment expression on the right.
//output 10
echo $x;
?>
//output 120
echo $x;
?>
//output 20
21
x *= y x=x*y Multiplication <?php
$x = 10;
$y = 6;
echo $x * $y;
?>
//output 60
echo $x;
?>
//output 2
echo $x;
?>
//output 3
var_dump($x == $y); //
returns true because
22
values are equal
?>
//output bool(true)
var_dump($x != $y); //
returns false because
values are equal
?>
23
var_dump($x > $y); //
returns true because $x
is greater than $y
?>
The PHP comparison operators are used to compare two values (number or
string):
24
one, then returns $x echo ++$x;
?>
//output 11
//output 10
//output 9
//output 10
25
if ($x == 100 and $y == 50){
echo "Hello world!"; }
?>
//Hello world!
//Hello world!
//Hello world!
<?php
$x = 100;
&& And $x && $y True if both $x and $y = 50;
$y are true
if ($x == 100 && $y == 50) {
echo "Hello world!";
}
?>
//Hello world!
26
?>
//Hello world!
//Hello world!
//Hello world!
27
Oper Name Example Result Show it
ator
//output
Array ( [a] => red [b] => green [c] => blue [d] => yellow )
//output
bool(false)
28
var_dump($x != $y);
?>
//output
bool(true)
bool(true)
//output
bool(true)
29
if...else statement - executes some code if a condition is true and
another code if that condition is false
if...elseif....else statement - executes different codes for more than
two conditions
switch statement - selects one of many blocks of code to be executed
Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is
less than 20:
Example
<?php
$t = date("H");
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less
than 20, and "Have a good night!" otherwise:
31
Example
<?php
$t = date("H");
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is
less than 10, and "Have a good day!" if the current time is less than 20.
Otherwise it will output "Have a good night!":
Example
<?php
$t = date("H");
31
PHP - The switch Statement
The switch statement is used to perform different actions based on different
conditions.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
32
Example
<?php
$favcolor = "red";
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 while loops execute a block of code while the specified condition is true.
PHP Loops
Often when you write code, you want the same block of code to run over and
over again in a row. Instead of adding several almost equal code-lines in a
script, we can use loops to perform a task like this.
33
The PHP while Loop
The while loop executes a block of code as long as the specified condition is
true.
Syntax
while (condition is true) {
code to be executed;
}
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop
will continue to run as long as $x is less than, or equal to 5 ($x <= 5). $x will
increase by 1 each time the loop runs ($x++):
Example
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Syntax
do {
code to be executed;
} while (condition is true);
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:
34
Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Notice that in a do while loop the condition is tested AFTER executing the
statements within the loop. This means that the do while loop would execute
its statements at least once, even if the condition is false the first time.
The example below sets the $x variable to 6, then it runs the loop, and then
the condition is checked:
Example
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
The for loop and the foreach loop will be explained in the next chapter.
Syntax
for (init counter; test counter; increment counter) {
code to be executed;
}
35
Parameters:
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to
$value and the array pointer is moved by one, until it reaches the last array
element.
The following example demonstrates a loop that will output the values of the
given array ($colors):
Example
<?php
$colors = array("red", "green", "blue", "yellow");
36
The real power of PHP comes from its functions; it has more than 1000 built-
in functions.
Syntax
function functionName() {
code to be executed;
}
Note: A function name can start with a letter or underscore (not a number).
Tip: Give the function a name that reflects what the function does!
Example
<?php
function writeMsg() {
echo "Hello world!";
}
37
PHP Function Arguments
Information can be passed to functions through arguments. An argument is just
like a variable.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
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("Ali");
familyName("Mohammed");
familyName("Sameer Jim");
familyName("Borge");
?>
The following example has a function with two arguments ($fname and $year):
Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Ali", "1975");
familyName("Mohammed", "1978");
familyName("Sameer", "1983");
?>
38
PHP Default Argument Value
The following example shows how to use a default parameter. If we call the
function setHeight() without arguments it takes the default value as argument:
Example
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Example
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
39
PHP 5 Arrays
An array stores multiple values in one single variable:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?
An array can hold many values under a single name, and you can access the
values by referring to an index number.
array();
41
PHP Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The following example creates an indexed array named $cars, assigns three
elements to it, and then prints a text containing the array values:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
41
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>"; }
?>
or:
$age['Ali'] = "35";
$age['Mohammed'] = "37";
$age['Sameer'] = "20";
Example
<?php
$age = array("Ali"=>"35", "Mohammed"=>"37", "Sameer"=>"20");
echo "Ali is " . $age['Ali'] . " years old.";
?>
Example
<?php
$age = array("Ali"=>"35", "Mohammed"=>"37", "Sameer"=>"20");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>"; }
?>
42
PHP 5 Multidimensional Arrays
Earlier , we have described arrays that are a single list of key/value pairs.
However, sometimes you want to store values with more than one key.
PHP understands multidimensional arrays that are two, three, four, five, or
more levels deep. However, arrays more than three levels deep are hard to
manage for most people.
43
We can store the data from the table above in a two-dimensional array, like
this:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two
indices: row and column.
To get access to the elements of the $cars array we must point to the two
indices (row and column):
Example
44
We can also put a for loop inside another for loop to get the elements of the
$cars array (we still have to point to the two indices):
Example
45
PHP 5 Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order,
descending or ascending.
Example
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
</body>
</html>
The following example sorts the elements of the $numbers array in ascending
numerical order:
46
Example (same as the above example)
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
The following example sorts the elements of the $numbers array in descending
numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
} ?>
47
Sort Array (Ascending Order), According to
Value - asort()
The following example sorts an associative array in ascending order, according
to the value:
Example
<?php
$age = array("Ali"=>"35", "Mohammed"=>"37", "Sameer"=>"20");
asort($age);
Example
Do this Example by yourself
Example
<?php
$age = array("Ali"=>"35", "Mohammed"=>"37", "Sameer"=>"20");
arsort($age);
48
Sort Array (Descending Order), According to
Key - krsort()
The following example sorts an associative array in descending order, according
to the key:
Example
<?php
$age = array("Ali"=>"35", "Mohammed"=>"37", "Sameer"=>"20");
krsort($age);
?>
Homework
49
Forms
PHP Registration Form using GET, POST Methods with Example
What is Form?
When you login into a website or into your mail box, you are interacting with a form.
Forms are used to get input from the user and submit it to the web server for
processing.
A form is an HTML tag that contains graphical user interface items such as input
box, check boxes radio buttons etc.
The form is defined using the <form>...</form> tags and GUI items are defined using
form elements such as input.
Create a form
We will use HTML tags to create a form. Below is the minimal list of things you need
to create a form.
51
Input fields such as input boxes, text areas, buttons,checkboxes etc.
<html>
<head>
<title>Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h2>Registration Form</h2>
</form>
</body>
</html>
Viewing the above code in a web browser displays the following form.
HERE,
51
<input type="hidden" name="form_submitted" value="1"/> is a hidden value
that is used to check whether the form has been submitted or not
<input type="submit" value="Submit"> is the button that when clicked submits
the form to the server for processing
<?php
$_POST['variable_name'];
?>
HERE,
52
<?php
$_GET['variable_name'];
?>
HERE,
Has not limitation of the length of the Has limitation on the length of the values
values since they are submitted via usually 255 characters. This is because the
the body of HTTP values are displayed in the URL. Note the
upper limit of the characters is dependent
on the browser.
Supports many different data types Supports only string data types because the
such as string, numeric, binary etc. values are displayed in the URL
Results cannot be book marked Results can be book marked due to the
visibility of the values in the URL
The below diagram shows the difference between get and post
53
Processing the registration form data
The registration form submits data to itself as specified in the action attribute of the
form.
When a form has been submitted, the values are populated in the $_POST super
global array.
We will use the PHP isset function to check if the form values have been filled in the
$_POST array and process the data.
We will modify the registration form to include the PHP code that processes the
data. Below is the modified code
54
<html>
<head>
<title>Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<p>
You have been registered as
<?php echo $_POST['firstname'] . ' ' . $_POST['lastname']; ?>
</p>
<h2>Registration Form</h2>
</form>
HERE,
If the form_fobmitted field hasn’t been filled in the $_POST[] array, the form is
displayed.
55
More examples
Simple search engine
We will design a simple search engine that uses the PHP_GET method as the form
submission type.
For simplicity’s sake, we will use a PHP If statement to determine the output.
We will use the same HTML code for the registration form above and make minimal
modifications to it.
<html>
<head>
<title>Simple Search Engine</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
Search Term:
<input type="text" name="search_term">
<br>
56
</form>
<?php endif; ?>
</body>
</html>
The diagram below shows the URL for the above results
Note the URL has displayed the value of search_term and form_submitted. Try to
enter anything different from GET then click on submit button and see what results
you will get.
We will modify the registration form code and include a check button that allows the
user to agree to the terms of service.
<html>
57
<head>
<title>Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<p>
You have been registered as
<?php echo $_POST['firstname'] . ' ' . $_POST['lastname']; ?>
</p>
<h2>Registration Form</h2>
form action="registration_form2.php" method="POST">
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname"><br>
Agree to Terms of Service: <input type="checkbox" name="agree"><br>
<input type="hidden" name="form_submitted" value="1" />
<input type="submit" value="Submit">
</form>
<?php endif; ?>
</body>
</html>
58
Fill in the first and last names
Note the Agree to Terms of Service checkbox has not been selected.
Click on back to the form link and then select the checkbox
Summary
59
Forms are used to get data from the users
Forms are created using HTML tags
Forms can be submitted to the server for processing using either POST or
GET method
Form values submitted via the POST method are encapsulated in the HTTP
body.
Form values submitted via the GET method are appended and displayed in
the URL.
Example
<html>
<body>
</body>
</html>
When the user fills out the form above and clicks the submit button, the form
data is sent for processing to a PHP file named "welcome.php". The form data is
sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The
"welcome.php" looks like this:
<html>
<body>
61
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
The same result could also be achieved using the HTTP GET method:
Example
<html>
<body>
</body>
</html>
<html>
<body>
</body>
</html>
The code above is quite simple. However, the most important thing is missing.
You need to validate form data to protect your script from malicious code.
This page does not contain any form validation, it just shows how you can send
and retrieve form data.
However, the next pages will show how to process PHP forms with security in
mind! Proper validation of form data is important to protect your form from
hackers and spammers!
61
GET vs. POST
Both GET and POST create an array (e.g. array( key => value, key2 => value2,
key3 => value3, ...)). This array holds key/value pairs, where keys are the
names of the form controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are super global ,
which means that they are always accessible, regardless of scope - and you can
access them from any function, class or file without having to do anything
special.
$_GET is an array of variables passed to the current script via the URL
parameters.
$_POST is an array of variables passed to the current script via the HTTP POST
method.
Note: GET should NEVER be used for sending passwords or other sensitive
information!
However, because the variables are not displayed in the URL, it is not possible
to bookmark the page.
62
PHP Form Validation
Think SECURITY when processing PHP forms!
These pages will show how to process PHP forms with security in mind. Proper
validation of form data is important to protect your form from hackers and
spammers!
The HTML form we will be working at in these chapters, contains various input
fields: required and optional text fields, radio buttons, and a submit button:
63
The validation rules for the form above are as follows:
First we will look at the plain HTML code for the form:
Text Fields
The name, email, and website fields are text input elements, and the comment
field is a textarea. The HTML code looks like this:
64
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
When the form is submitted, the form data is sent with method="post".
So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page
itself, instead of jumping to a different page. This way, the user will get error
messages on the same page as the form.
If PHP_SELF is used in your page then a user can enter a slash (/) and then
some Cross Site Scripting (XSS) commands to execute.
65
Assume we have the following form in a page named "test_form.php":
Now, if a user enters the normal URL in the address bar like
"http://www.example.com/test_form.php", the above code will be translated to:
So far, so good.
However, consider that a user enters the following URL in the address bar:
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/scr
ipt%3E
This code adds a script tag and an alert command. And when the page loads,
the JavaScript code will be executed (the user will see an alert box). This is just
a simple and harmless example how the PHP_SELF variable can be exploited.
Be aware of that any JavaScript code can be added inside the <script>
tag! A hacker can redirect the user to a file on another server, and that file can
hold malicious code that can alter the global variables or submit the form to
another address to save the user data, for example.
66
The exploit attempt fails, and no harm is done!
When we use the htmlspecialchars() function; then if a user tries to submit the
following in a text field:
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as HTML escaped code,
like this:
<script>location.href('http://www.hacked.com')</script>
We will also do two more things when the user submits the form:
1. Strip unnecessary characters (extra space, tab, newline) from the user
input data (with the PHP trim() function)
2. Remove backslashes (\) from the user input data (with the PHP
stripslashes() function)
The next step is to create a function that will do all the checking for us (which is
much more convenient than writing the same code over and over again).
Now, we can check each $_POST variable with the test_input() function, and
the script looks like this:
67
Example
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?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;
}
?>
68
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Notice that at the start of the script, we check whether the form has been
submitted using $_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is
69
POST, then the form has been submitted - and it should be validated. If it has
not been submitted, skip the validation and display a blank form.
However, in the example above, all input fields are optional. The script works
fine even if the user does not enter any data.
71
In the previous chapter, all input fields were optional.
In the following code we have added some new variables: $nameErr, $emailErr,
$genderErr, and $websiteErr. These error variables will hold error messages for
the required fields. We have also added an if else statement for each $_POST
variable. This checks if the $_POST variable is empty (with the
PHP empty() function). If it is empty, an error message is stored in the different
error variables, and if it is not empty, it sends the user input data through
the test_input() function:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
71
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
72
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
73
Example
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])
;?>">
</form>
The next step is to validate the input data, that is "Does the Name field contain
only letters and whitespace?", and "Does the E-mail field contain a valid e-mail
address syntax?", and if filled out, "Does the Website field contain a valid
URL?".
74
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
In the code below, if the e-mail address is not well-formed, then store an error
message:
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
75
PHP - Validate Name, E-mail, and URL
Now, the script looks like this:
Example
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also
allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
76
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
Then, we also need to show which radio button that was checked. For this, we
must manipulate the checked attribute (not the value attribute for radio
buttons):
Gender:
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
77
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="other") echo "checked";?>
value="other">Other
Syntax
date(format,timestamp)
Parameter Description
Here are some characters that are commonly used for dates:
78
Other characters, like"/", ".", or "-" can also be inserted between the characters
to add additional formatting.
Outputs
79
PHP 5 Include Files
The include (or require) statement takes all the text/code/markup that
exists in the specified file and copies it into the file that uses the include
statement.
Including files is very useful when you want to include the same PHP, HTML,
or text on multiple pages of a website.
The include and require statements are identical, except upon failure:
So, if you want the execution to go on and show users the output, even if the
include file is missing, use the include statement. Otherwise, in case of
FrameWork, CMS, or a complex PHP application coding, always use the require
statement to include a key file to the flow of execution. This will help avoid
compromising your application's security and integrity, just in-case one key file
is accidentally missing.
Including files saves a lot of work. This means that you can create a standard
header, footer, or menu file for all your web pages. Then, when the header
needs to be updated, you can only update the header include file.
Syntax
include 'filename';
or
require 'filename';
81
PHP include Examples
Example 1
Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "<p>Copyright © 1999-" . date("Y") . " W3Schools.com</p>";
?>
Example
<html>
<body>
</body>
</html>
Output
Some text.
81
Example 2
Assume we have a file called "vars.php", with some variables defined:
<?php
$color='red';
$car='BMW';
?>
Then, if we include the "vars.php" file, the variables can be used in the calling
file:
Example
<html>
<body>
<h1>Welcome to my home page!</h1>
<?php include 'vars.php';
echo "I have a $color $car.";
?>
</body>
</html>
output
However, there is one big difference between include and require; when a file is
included with the include statement and PHP cannot find it, the script will
continue to execute:
82
Example
<html>
<body>
</body>
</html>
output
If we do the same example using the require statement, the echo statement
will not be executed because the script execution dies after
the require statement returned a fatal error:
Example
<html>
<body>
</body>
</html>
output
Use include when the file is not required and application should continue when
file is not found.
83
Files
File Handling
File handling is an important part of any web application. You often need to open and
process a file for different tasks.
You can do a lot of damage if you do something wrong. Common errors are: editing the wrong
file, filling a hard-drive with garbage data, and deleting the content of a file by accident.
Assume we have a text file called "webdictionary.txt", stored on the server, that looks like this:
The PHP code to read the file and write it to the output buffer is as follows
(the readfile() function returns the number of bytes read on success):
84
The readfile() function is useful if all you want to do is open up a file and read its contents.
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:
85
PHP Read File - fread()
The fread() function reads from an open file.
The first parameter of fread() contains the name of the file to read from and the second
parameter specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
86
PHP Close File - fclose()
The fclose() function is used to close an open file.
It's a good programming practice to close all files after you have finished with them. You don't
want an open file running around on your server taking up resources!The fclose() requires the
name of the file (or a variable that holds the filename) we want to close:<?php$myfile =
fopen("webdictionary.txt", "r");// some code to be executed....
fclose($myfile);
?>
The example below outputs the first line of the "webdictionary.txt" file:
Note: After a call to the fgets() function, the file pointer has moved to the next line.
The feof() function is useful for looping through data of unknown length.
The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:
87
PHP Read Single Character - fgetc()
The fgetc() function is used to read a single character from a file.
The example below reads the "webdictionary.txt" file character by character, until end-of-file
is reached:
Note: After a call to the fgetc() function, the file pointer moves to the next character.
If you use fopen() on a file that does not exist, it will create it, given that the file is opened for
writing (w) or appending (a).
The example below creates a new file called "testfile.txt". The file will be created in the same
directory where the PHP code resides:
88
Example
$myfile = fopen("testfile.txt", "w")
The first parameter of fwrite() contains the name of the file to write to and the second
parameter is the string to be written.
The example below writes a couple of names into a new file called "newfile.txt":
Example
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the
string $txt that first contained "Ahmed Abbas" and second contained "Mohammed Ali". After
we finished writing, we closed the file using the fclose() function.
Ahmed Abbas
Mohammed Ali
89
PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we open an
existing file for writing. All the existing data will be ERASED and we start with an empty file.
In the example below we open our existing file "newfile.txt", and write some new data into it:
Example
If we now open the "newfile.txt" file, both Ahmed and Mohammed have vanished, and only the
data we just wrote is present:
Mickey Mouse
Minnie Mouse
However, with ease comes danger, so always be careful when allowing file uploads!
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
91
Some rules to follow for the HTML form above:
Without the requirements above, the file upload will not work.
The type="file" attribute of the <input> tag shows the input field as a file-select control,
with a "Browse" button next to the input control
The form above sends data to a file called "upload.php", which we will create next.
91
PHP script explained:
$target_dir = "uploads/" - specifies the directory where the file is going to be placed
$target_file specifies the path of the file to be uploaded
$uploadOk=1 is not used yet (will be used later)
$imageFileType holds the file extension of the file (in lower case)
Next, check if the image file is an actual image or a fake image
Note: You will need to create a new directory called "uploads" in the directory where
"upload.php" file resides. The uploaded files will be saved there.
First, we will check if the file already exists in the "uploads" folder. If it does, an error message
is displayed, and $uploadOk is set to 0:
92
Limit File Size
The file input field in our HTML form above is named "fileToUpload".
Now, we want to check the size of the file. If the file is larger than 500KB, an error message is
displayed, and $uploadOk is set to 0:
93
Complete Upload File PHP Script
The complete "upload.php" file now looks like this:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0; } }
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
} }
?>
94
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.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
We then retrieve the value of the cookie "user" (using the global variable
$_COOKIE). We also use the isset() function to find out if the cookie is set:
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400
= 1 day
?>
<html>
<body>
<?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];
}
?>
95
</body>
</html>
Note: The setcookie() function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URLencoded when sending the
cookie, and automatically decoded when received (to prevent URLencoding,
use setrawcookie() instead).
Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?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>
96
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the
past:
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
97
A session is a way to store information (in variables) to be used across
multiple pages.
So; Session variables hold information about one single user, and are available
to all pages in one application.
Tip: If you need a permanent storage, you may want to store the data in
a database.
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>
98
Note: The session_start() function must be the very first thing in your
document. Before any HTML tags.
Notice that session variables are not passed individually to each new page,
instead they are retrieved from the session we open at the beginning of each
page (session_start()).
Also notice that all session variable values are stored in the global $_SESSION
variable:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Another way to show all the session variable values for a user session is to run
the following code:
99
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Most sessions set a user-key on the user's computer that looks something like
this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on
another page, it scans the computer for a user-key. If there is a match, it
accesses that session, if not, it starts a new session.
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
111
Destroy a PHP Session
To remove all global session variables and destroy the session,
use session_unset() and session_destroy():
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
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
111
Database Queries
A query is a question or a request.
112
Should I Use MySQLi or PDO?
If you need a short answer, it would be "Whatever you like".
PDO will work on 12 different database systems, whereas MySQLi will only work
with MySQL databases.
So, if you have to switch your project to use another database, PDO makes the
process easy. You only have to change the connection string and a few queries.
With MySQLi, you will need to rewrite the entire code - queries included.
server anme=localhost
User name=root;
Password="";
113
PHP is an amazing and popular language!
// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
114
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.
115
PHP Create a MySQL Database
A database consists of one or more tables.
116
Note: When you create a new database, you must only specify the first three
arguments to the mysqli object (servername, username and password).
Tip: If you have to use a specific port, add an empty string for the database-
name argument, like this: new mysqli("localhost", "username", "password", "",
port)
117
Note: The following PDO example create a database named "myDBPDO":
118
Tip: A great benefit of PDO is that it has 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. In the catch block above we echo the SQL statement and the generated
error message.
119
PHP Insert Data Into MySQL
Insert Data Into MySQL Using MySQLi and
PDO
After a database and a table have been created, we can start adding data in
them.
The INSERT INTO statement is used to add new records to a MySQL table:
In the previous chapter we created an empty table named "MyGuests" with five
columns: "id", "firstname", "lastname", "email" and "reg_date". Now, let us fill
the table with data.
111
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
mysqli_close($conn);
?>
111
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
112
The following examples add three new records to the "MyGuests" table:
113
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());
}
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
114
The PDO way is a little bit different:
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn = null;
?>
115
Prepared Statements and Bound Parameters
A prepared statement is a feature used to execute the same (or similar) SQL
statements repeatedly with high efficiency.
116
Prepared Statements in MySQLi
The following example uses prepared statements and bound parameters in
MySQLi:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
117
Code lines to explain from the example above:
This function binds the parameters to the SQL query and tells the database
what the parameters are. The "sss" argument lists the types of data that the
parameters are. The s character tells mysql that the parameter is a string.
i - integer
d - double
s - string
b - BLOB
By telling mysql what type of data to expect, we minimize the risk of SQL
injections.
Note: If we want to insert any data from external sources (like user input), it is
very important that the data is sanitized and validated.
118
Prepared Statements in PDO
The following example uses prepared statements and bound parameters in
PDO:
119
Select Data From a MySQL Database
The SELECT statement is used to select data from one or more tables:
121
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:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
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);
?>
121
You can also put the result in an HTML table:
// 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) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]."
".$row["lastname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
It selects the id, firstname and lastname columns from the MyGuests table and
displays it in an HTML table:
122
Example (PDO)
<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";
function current() {
return "<td style='width:150px;border:1px solid black;'>" .
parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->
fetchAll())) as $k=>$v) {
echo $v; } }
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
123
Delete Data From a MySQL Table Using
MySQLi and PDO
The DELETE statement is used to delete records from a table:
Notice the WHERE clause in the DELETE syntax: The WHERE clause
specifies which record or records that should be deleted. If you omit the WHERE
clause, all records will be deleted!
The following examples delete the record with id=3 in the "MyGuests" table:
124
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();
?>
125
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());
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn); }
mysqli_close($conn);
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
// use exec() because no results are returned
$conn->exec($sql);
echo "Record deleted successfully";}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
126
After the record is deleted, the table will look like this:
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!
The following examples update the record with id=2 in the "MyGuests" table:
127
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);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
mysqli_close($conn);
?>
128
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare statement
$stmt = $conn->prepare($sql);
After the record is updated, the table will look like this:
129
Limit Data Selections From a MySQL Database
MySQL provides a LIMIT clause that is used to specify the number of records to
return.
The LIMIT clause makes it easy to code multi page results or pagination with
SQL, and is very useful on large tables. Returning a large number of records can
impact on performance.
Assume we wish to select all records from 1 - 30 (inclusive) from a table called
"Orders". The SQL query would then look like this:
When the SQL query above is run, it will return the first 30 records.
The SQL query below says "return only 10 records, start on record 16 (OFFSET
15)":
You could also use a shorter syntax to achieve the same result:
Notice that the numbers are reversed when you use a comma.
131
Complete user registration system using PHP and MySQL database
In this lecture, we will go through the complete process of creating a user registration
system where users can create an account by providing username, email and password,
login and logout using PHP and MySQL. I will also show you how you can make some
pages accessible only to logged in users. Any other user not logged in will not be able to
access the page.
id
username - varchar(100)
email - varchar(100)
password - varchar(100)
131
Or you can create it on the MySQL prompt using the following SQL script:
Now create a folder called registration in a directory accessible to our server. i.e
create the folder inside htdocs (if you are using XAMPP server) or inside www (if
you are using wampp server).
Registering a user
132
Open the register.php file and paste the following code in it:
regiser.php:
133
<label>Confirm password</label>
<input type="password" name="password_2">
</div>
<div class="input-group">
<button type="submit" class="btn"
name="reg_user">Register</button>
</div>
<p>
Already a member? <a href="login.php">Sign in</a>
</p>
</form>
</body>
</html>
First is that our form's action attribute is set to register.php. This means that
when the form submit button is clicked, all the data in the form will be submitted
to the same page (register.php). The part of the code that receives this form
data is written in the server.php file and that's why we are including it at the
very top of the register.php file.
Notice also that we are including the errors.php file to display form errors. We
will come to that soon.
As you can see in the head section, we are linking to a style.css file. Open up
the style.css file and paste the following CSS in it:
* {
margin: 0px;
padding: 0px;
}
body {
font-size: 120%;
134
background: #F8F8FF;
}
.header {
width: 30%;
margin: 50px auto 0px;
color: white;
background: #5F9EA0;
text-align: center;
border: 1px solid #B0C4DE;
border-bottom: none;
border-radius: 10px 10px 0px 0px;
padding: 20px;
}
form, .content {
width: 30%;
margin: 0px auto;
padding: 20px;
border: 1px solid #B0C4DE;
background: white;
border-radius: 0px 0px 10px 10px;
}
.input-group {
margin: 10px 0px 10px 0px;
}
.input-group label {
display: block;
text-align: left;
margin: 3px;
}
.input-group input {
height: 30px;
135
width: 93%;
padding: 5px 10px;
font-size: 16px;
border-radius: 5px;
border: 1px solid gray;
}
.btn {
padding: 10px;
font-size: 15px;
color: white;
background: #5F9EA0;
border: none;
border-radius: 5px;
}
.error {
width: 92%;
margin: 0px auto;
padding: 10px;
border: 1px solid #a94442;
color: #a94442;
background: #f2dede;
border-radius: 5px;
text-align: left;
}
.success {
color: #3c763d;
background: #dff0d8;
border: 1px solid #3c763d;
margin-bottom: 20px;
}
136
Let's now write the code that will receive information submitted from the form and
store (register) the information in the database. As promised earlier, we do this in
the server.php file.
server.php
<?php
session_start();
// initializing variables
$username = "";
$email = "";
$errors = array();
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db,
$_POST['password_1']);
$password_2 = mysqli_real_escape_string($db,
$_POST['password_2']);
138
VALUES('$username', '$email', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
// ...
The comments in the code pretty much explain everything, but I'll highlight a few
things here.
All the data is received from the form and checked to make sure that the user
correctly filled the form. Passwords are also compared to make sure they match.
If no errors were encountered, the user is registered in the users table in the
database with a hashed password. The hashed password is for security reasons.
It ensures that even if a hacker manages to gain access to your database, they
would not be able to read your password.
But error messages are not displaying now because our errors.php file is still
empty. To display the errors, paste this code in the errors.php file.
139
<?php if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
When a user is registered in the database, they are immediately logged in and
redirected to the index.php page.
Login user
Logging a user in is an even easier thing to do. Just open the login page and put
this code inside it:
141
<input type="text" name="username" >
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password">
</div>
<div class="input-group">
<button type="submit" class="btn"
name="login_user">Login</button>
</div>
<p>
Not yet a member? <a href="register.php">Sign up</a>
</p>
</form>
</body>
</html>
Now the code that logs the user in is to be written in the same server.php file.
So open the server.php file and add this code at the end of the file:
// ...
// LOGIN USER
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
141
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username'
AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}else {
array_push($errors, "Wrong username/password
combination");
}
}
}
?>
Again all this does is check if the user has filled the form correctly, verifies that
their credentials match a record from the database and logs them in if it does.
After logging in, the user is redirected them to the index.php file with a success
message.
Now let's see what happens in the index.php file. Open it up and paste the
following code in it:
<?php
session_start();
if (!isset($_SESSION['username'])) {
$_SESSION['msg'] = "You must log in first";
header('location: login.php');
}
142
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header("location: login.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="header">
<h2>Home Page</h2>
</div>
<div class="content">
<!-- notification message -->
<?php if (isset($_SESSION['success'])) : ?>
<div class="error success" >
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</h3>
</div>
<?php endif ?>
143
<p>Welcome <strong><?php echo $_SESSION['username'];
?></strong></p>
<p> <a href="index.php?logout='1'" style="color:
red;">logout</a> </p>
<?php endif ?>
</div>
</body>
</html>
The first if statement checks if the user is already logged in. If they are not logged in,
they will be redirected to the login page. Hence this page is accessible to only logged in
users. If you'd like to make any page accessible only to logged in users, all you have
to do is place this if statement at the top of the file.
The second if statement checks if the user has clicked the logout button. If yes,
the system logs them out and redirects them back to the login page.
Now go on, customize it to suit your needs and build an awesome site. If you
have any worries or anything you need to clarify, leave it in the comments below
and help will come.
144