Chapter 4
Chapter 4
Chapter 4
Basics of PHP
4.1 Introduction
PHP scripts are executed on the web server and the result is sent to the browser.
What is PHP
PHP stands for Hypertext Preprocessor. PHP is a powerful and widely-used open source server-
side scripting language to write dynamically generated web pages. PHP scripts are executed on
the server and the result is sent to the browser as plain HTML.
PHP can be integrated with the number of popular databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server.
PHP can be embedded within normal HTML web pages. That means inside your HTML
documents you'll have PHP statements as shown in Example 4.1:
Example 4.1
1. <!DOCTYPE HTML>
2. <html>
3. <head>
4. <title>PHP Application</title>
5. </head>
6. <body>
7. <?php
8. // Display greeting message
9. echo 'Hello World!';
10. ?>
11. </body>
12. </html>
1
You can collect data from a web form such as user information, email, credit card
information and much more.
You can send emails to the users of your website.
You can send and receive cookies to track the visitor of your website.
You can store, delete, and modify information in your database.
You can restrict unauthorized access to your website.
You can encrypt data for safe transmission over internet.
We suppose that you have successfully installed WampServer on your computer to start your
first PHP application. In this section we will create a very simple PHP script that displays the
text "Hello, world!" in the browser window. Ok, click on the WampServer icon somewhere on
your Windows task bar and select the "www directory". Alternatively you can access the "www"
directory through C:\wamp\www. Create a subdirectory in "www" let's say "project".
Now open up your favorite code editor and create a new PHP file. Start with an empty window
and type the following code:
Example 4.2:
1. <?php
2. // Simple greeting message
3. echo "Hello, world!";
4. ?>
Now save this file as "hello.php" in your project folder (located at C:\wamp\www\project), and
view the result in your browser through visiting this URL: http://localhost/project/hello.php.
Alternatively you can access the "hello.php" file through selecting the localhost option from the
WampSever menu on the taskbar.
A PHP script starts with the <?php and ends with the ?> tag.
2
The PHP delimiter <?php and ?> in the following example simply tells the PHP engine to treat
the enclosed code block as PHP code, rather than simple HTML.
Example 4.3:
1. <?php
2. // Some code to be executed
3. echo "Hello, world!";
4. ?>
Every PHP statement end with a semicolon (;) — this tells the PHP engine that the end of the
current statement has been reached.
Example 4.4:
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>A Simple PHP File</title>
6. </head>
7. <body>
8. <h1><?php echo "Hello, world!"; ?></h1>
9. </body>
10. </html>
Example 4.4 shows how you can embed PHP codes within HTML to create well-formed
dynamic web pages. If you view the source code of the resulting web page in your browser, the
only difference you will see is, the PHP code <?php echo "Hello, world!"; ?> has been
replaced with the output "Hello, world!".
When you run this code the PHP engine executed the instructions between the <?php … ?> tags
and leave rest of the thing as it is. At the end, the web server sends the final output back to your
browser which is completely in HTML.
3
PHP Comments
A comment is simply text that is ignored by the PHP engine. The purpose of comments is to
make the code more readable. It may help other developer (or you in the future when you edit the
source code) to understand what you were trying to do with the PHP.
PHP supports single-line as well as multi-line comments. To write a single-line comment start
the line with either two slashes (//) or a hash symbol (#) as shown in Example 4.5:
Example 4.5
1. <?php
2. // This is a single line comment
3. # This is also a single line comment
4. echo "Hello, world!";
5. ?>
However to write multi-line comments, start the comment with a slash followed by an asterisk
(/*) and end the comment with an asterisk followed by a slash (*/), like Example 4.6:
Example 4.6
1. <?php
2. /*
3. This is a multiple line comment block
4. that spans across more than
5. one line
6. */
7. echo "Hello, world!";
8. ?>
Example 4.7
1. <?php
2. // Assign value to variable
3. $color = "blue";
4.
5. // Try to print variable value
4
6. echo "The color of the sky is " . $color . "<br>";
7. echo "The color of the sky is " . $Color . "<br>";
8. echo "The color of the sky is " . $COLOR . "<br>";
9. ?>
If you try to run the above example code it will only display the value of the variable $color and
produce the "Undefined variable" warning for the variable $Color and $COLOR.
However keywords, function and classes names are case-insensitive. As a result calling the
gettype() or GETTYPE() produce the same result.
Example 4.8
1. <?php
2. // Assign value to variable
3. $color = "blue";
4.
5. // Get the type of a variable
6. echo gettype($color) . "<br>";
7. echo GETTYPE($color) . "<br>";
8. ?>
If you try to run the above example code both the functions gettype() and GETTYPE() gives the
same output, which is: string.
Variables are used for storing values that can change over the course of a script, whereas the
constants are used for storing fixed values that doesn't change.
Variables in PHP
Variables are used to store data, like text strings, numbers or arrays.
In PHP, a variable does not need to be declared before adding a value to it. PHP
automatically converts the variable to the correct data type, depending on its value.
After declaring a variable it can be reused throughout the code.
The assignment operator (=) used to assign value to a variable.
5
In PHP variable can be declared as: $var_name = value;
Example 4.9
1. <?php
2. $txt = "Hello World!";
3. $number = 10;
4. ?>
In the above example we have created two variables where first one has assigned with a string
value and the second has assigned with a number.
All variables in PHP start with a dollar 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 in PHP can only contain alpha-numeric characters and underscores (A-
z, 0-9, and _).
A variable name cannot contain spaces.
Note: Variable names in PHP are case sensitive, it means $x and $X are two different variables.
So be careful while defining variable names.
Constants in PHP
A constant is an identifier (name) for a simple value. A constant value cannot change during the
execution of the script (except for magic constants). Constants are useful for storing data that
doesn't change while the script is running. Common examples of such data include configuration
settings (such as database usernames and passwords).
Constants are defined using define () function, which accepts two arguments: the name of
the constant, and its value. Here is an example of defining and using a constant in a script:
Example 4.10
1. <?php
2. // Defining constants
3. define("PROGRAM", "PHP");
4. define("VERSION", "5.5.14");
6
5. // Using constants
6. echo 'Current ' . PROGRAM . ' version is: ' . VERSION;
7. ?>
Name of constants must follow the same rules as variable names, which means a valid constant
name must starts with a letter or underscore, followed by any number of letters, numbers, or
underscores, with one exception: the $ prefix is not required for constant names.
PHP supports total eight primitive data types: Integer, Floating point number or Float, String,
Booleans, Array, Object, resource and NULL.
The values assigned to a PHP variable may be of different data types including simple string and
numeric types to more complex data types like arrays and objects. PHP supports total eight data
types which are used to construct variables.
PHP Integers
Integers are whole numbers, without a decimal point (..., -2, -1, 0, 1, 2, ...). Integers can be
specified in decimal (base 10), hexadecimal (base 16 - prefixed with 0x) or octal (base 8 -
prefixed with 0) notation, optionally proceeded by a sign (- or +).
Example 4.11
1. <?php
2. $a = 123; // decimal number
3. var_dump($a);
4. echo "<br>";
5.
6. $b = -123; // a negative number
7. var_dump($b);
8. echo "<br>";
9.
10. $c = 0x1A; // hexadecimal number
11. var_dump($c);
12. echo "<br>";
7
13.
14. $d = 0123; // octal number
15. var_dump($d);
16. ?>
Note: Since PHP 5.4+ you can also specify integers in binary (base 2) notation. To use binary
notation precede the number with 0b (e.g. $var = 0b11111111;).
PHP Strings
Strings are sequences of characters, where every character is the same as a byte. A string can
hold letters, numbers, and special characters and it can be as large as up to 2GB (2147483647
bytes maximum). The simplest way to specify a string is to enclose it in single quotes (e.g. 'Hello
world!'), however you can also use double quotes ("Hello world!").
Example 4.12
1. <?php
2. $a = 'Hello world!';
3. echo $a;
4. echo "<br>";
5.
6. $b = "Hello world!";
7. echo $b;
8. echo "<br>";
9.
10. $c = 'Stay here, I\'ll be back.';
11. echo $c;
12. ?>
Floating point numbers (also known as "floats", "doubles", or "real numbers") are decimal or
fractional numbers, like demonstrated in the example below.
Example 4.13
1. <?php
2. $a = 1.234;
3. var_dump($a);
4. echo "<br>";
5.
6. $b = 10.2e3;
7. var_dump($b);
8. echo "<br>";
9.
10. $c = 4E-10;
8
11. var_dump($c);
12. ?>
PHP Booleans
Booleans are like a switch it has only two possible values either 1 (true) or 0 (false).
Example 4.14
1. <?php
2. // Assign the value TRUE to a variable
3. $show_error = True;
4. var_dump($show_error);
5. ?>
PHP Arrays
An array is a variable that can hold more than one value at a time. It is useful to aggregate a
series of related items together, for example a set of country or city names.
An array is formally defined as an indexed collection of data values. Each index (also known as
the key) of an array is unique and references a corresponding value
Example 4.15
1. <?php
2. $colors = array("Red", "Green", "Blue");
3. var_dump($colors);
4. echo "<br>";
5.
6. $color_codes = array(
7. "Red" => "#ff0000",
8. "Green" => "#00ff00",
9. "Blue" => "#0000ff"
10. );
11. var_dump($color_codes);
12. ?>
PHP Objects
An object is a data type that not only allows storing data but also information on, how to process
that data. An object is a specific instance of a class which serves as templates for objects. Objects
are created based on this template via the new keyword.
9
Every object has properties and methods corresponding to those of its parent class. Every object
instance is completely independent, with its own properties and methods, and can thus be
manipulated independently of other objects of the same class.
Example 4.16
1. <?php
2. // Class definition
3. class greeting{
4. // properties
5. public $str = "Hello World!";
6.
7. // methods
8. function show_greeting(){
9. return $this->str;
10. }
11. }
12.
13. // Create object from class
14. $message = new greeting;
15. var_dump($message);
16. ?>
Tip: The data elements stored within an object are referred to as its properties and the
information, or code which describing how to process the data is called the methods of the
object.
PHP NULL
The special NULL value is used to represent empty variables in PHP. A variable of type NULL
is a variable without any data. NULL is the only possible value of type null.
Example 4.17
1. <?php
2. $a = NULL;
3. var_dump($a);
4. echo "<br>";
5.
6. $b = "Hello World!";
7. $b = NULL;
8. var_dump($b);
9. ?>
10
When a variable is created without a value in PHP like $var; it is automatically assigned a value
of null. Many novice PHP developers mistakenly considered both $var1 = NULL; and $var2 =
""; are the same, but this is not true. Both variables are different — the $var1 has null value
while $var2 indicates no value assigned to it.
PHP Resources
Example 4.18
1. <?php
2. // Open a file for reading
3. $handle = fopen("note.txt", "r");
4. var_dump($handle);
5. echo "<br>";
6.
7. // Connect to MySQL database server with default setting
8. $link = mysql_connect("localhost", "root", "");
9. var_dump($link);
10. ?>
The PHP echo and print statements are used to display output in the browser.
The echo statement can output one or more strings. In general terms, the echo statement can
display anything that can be displayed to the browser, such as string, numbers, variables values,
the results of expressions etc.
Since echo is a language construct not actually a function (like if statement), you can use it
without parentheses e.g. echo or echo(). However, if you want to pass more than one parameter
to echo, the parameters must not be enclosed within parentheses.
The following example will show you how to display a string of text with the echo statement:
Example 4.19
1. <?php
2. // Displaying string of text
11
3. echo "Hello World!";
4. ?>
The output of the above PHP code will look something like this:
Hello World!
The following example will show you how to display HTML code using the echo statement:
Example 4.20
1. <?php
2. // Displaying HTML code
3. echo "<h4>This is a simple heading.</h4>";
4. echo "<h4 style='color: red;'>This is heading with style.</h4>"
5. ?>
The output of the above PHP code will look something like this:
Display Variables
The following example will show you how to display variable using the echo statement:
Example 4.21
1. <?php
2. // Defining variables
3. $txt = "Hello World!";
4. $num = 123456789;
5. $colors = array("Red", "Green", "Blue");
6.
7. // Displaying variables
8. echo $txt;
9. echo "<br>";
10. echo $num;
11. echo "<br>";
12. echo $colors[0];
13. ?>
The output of the above PHP code will look something like this:
12
Hello World!
123456789
Red
You can also use the print statement (an alternative to echo) to display output to the browser.
Like echo the print is also a language construct and not a real function. So you can also use it
without parentheses like: print or print().
Both echo and print statement works exactly the same way except that the print statement can
only output one string, and always returns 1. That's why the echo statement considered
marginally faster than the print statement since it doesn't return any value.
The following example will show you how to display a string of text with the print statement
Example 4.22
1. <?php
2. // Displaying string of text
3. print "Hello World!";
4. ?>
The output of the above PHP code will look something like this:
Hello World!
The following example will show you how to display HTML code using the print statement:
Example 4.23
1. <?php
2. // Displaying HTML code
3. print "<h4>This is a simple heading.</h4>";
4. print "<h4 style='color: red;'>This is heading with
style.</h4>"
5. ?>
The output of the above PHP code will look something like this:
13
This is heading with style.
Display Variables
The following example will show you how to display variable using the print statement:
Example 4.24
1. <?php
2. // Defining variables
3. $txt = "Hello World!";
4. $num = 123456789;
5. $colors = array("Red", "Green", "Blue");
6.
7. // Displaying variables
8. print $txt;
9. print "<br>";
10. print $num;
11. print "<br>";
12. print $colors[0];
13. ?>
The output of the above PHP code will look something like this:
Hello World!
123456789
Red
String in PHP
You can also use double quotation marks ("). However, single and double quotation marks work
in different ways. Strings enclosed in single-quotes are treated almost literally, whereas strings
delimited by the double quotes replace variables with the string representations of their values as
well as specially interpreting certain escape sequences.
Here's an example to clarify the differences between single and double quoted strings:
Example 4.25
1. <?php
2. $my_str = 'World';
3. echo "Hello, $my_str!<br>"; // Displays: Hello World!
4. echo 'Hello, $my_str!<br>'; // Displays: Hello, $my_str!
5.
6. echo '<pre>Hello\tWorld!</pre>'; // Displays: Hello\tWorld!
7. echo "<pre>Hello\tWorld!</pre>"; // Displays: Hello World!
8. echo 'I\'ll be back'; // Displays: I'll be back
9. ?>
PHP provides many built-in functions for manipulating strings like calculating the length of a
string, find substrings or characters, replacing part of a string with different characters, take a
string apart, and many others. Here are the examples of some of these functions.
The strlen() function is used to calculate the number of characters inside a string. It also
includes the blank spaces inside the string.
Example 4.26
1. <?php
2. $my_str = 'Welcome to Tutorial Republic';
3.
4. // Outputs: 28
5. echo strlen($my_str);
6. ?>
15
Example 4.27
1. <?php
2. $my_str = 'The quick brown fox jumps over the lazy dog.';
3.
4. // Outputs: 9
5. echo str_word_count($my_str);
6. ?>
The str_replace() replaces all occurrences of the search text within the target string.
Example 4.28
1. <?php
2. $my_str = 'If the facts do not fit the theory, change the
facts.';
3.
4. // Display replaced string
5. echo str_replace("facts", "truth", $my_str);
6. ?>
You can optionally pass the fourth argument to the str_replace() function to know how many
times the string replacements was performed, like this.
Example 4.29
1. <?php
2. $my_str = 'If the facts do not fit the theory, change the
facts.';
3.
4. // Perform string replacement
5. str_replace("facts", "truth", $my_str, $count);
6.
7. // Display number of replacements performed
8. echo "The text was replaced $count times.";
9. ?>
16
Reversing a String
Example 4.30
1. <?php
2. $my_str = 'You can do anything, but not everything.';
3.
4. // Display reversed string
5. echo strrev($my_str);
6. ?>
Operators in PHP
Operators are symbols that tell the PHP processor to perform certain actions. For example, the
addition (+) symbol is an operator that tells PHP to add two variables or values, while the
greater-than (>) symbol is an operator that tells PHP to compare two values.
The arithmetic operators are used to perform common arithmetical operations, such as addition,
subtraction, multiplication etc. Here is a complete list of PHP's arithmetic operators:
The following example will show you these arithmetic operators in action:
Example 4.31
17
1. <?php
2. $x = 10;
3. $y = 4;
4. echo($x + $y); // 0utputs: 14
5. echo($x - $y); // 0utputs: 6
6. echo($x * $y); // 0utputs: 40
7. echo($x / $y); // 0utputs: 2.5
8. echo($x % $y); // 0utputs: 2
9. ?>
The following example will show you these assignment operators in action:
Example 4.32
1. <?php
2. $x = 10;
3. echo $x; // Outputs: 10
4.
5. $x = 20;
6. $x += 30;
7. echo $x; // Outputs: 50
8.
9. $x = 50;
10. $x -= 20;
11. echo $x; // Outputs: 30
12. $x = 5;
13. $x *= 25;
14. echo $x; // Outputs: 125
15.
16. $x = 50;
17. $x /= 10;
18. echo $x; // Outputs: 5
19.
20. $x = 100;
21. $x %= 15;
18
22. echo $x; // Outputs: 10
23. ?>
The comparison operators are used to compare two values in a Boolean fashion.
The following example will show you these comparison operators in action:
Example 4.33
<?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z); // Outputs: boolean true
var_dump($x === $z); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x !== $z); // Outputs: boolean true
var_dump($x < $y); // Outputs: boolean true
var_dump($x > $y); // Outputs: boolean false
var_dump($x <= $y); // Outputs: boolean true
var_dump($x >= $y); // Outputs: boolean false
?>
19
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
The following example will show you these increment and decrement operators in action:
Example 4.34
1. <?php
2. $x = 10;
3. echo ++$x; // Outputs: 11
4. echo $x; // Outputs: 11
5.
6. $x = 10;
7. echo $x++; // Outputs: 10
8. echo $x; // Outputs: 11
9.
10. $x = 10;
11. echo --$x; // Outputs: 9
12. echo $x; // Outputs: 9
13.
14. $x = 10;
15. echo $x--; // Outputs: 10
16. echo $x; // Outputs: 9
17. ?>
The following example will show you these logical operators in action:
Example 4.35
1. <?php
2. $year = 2014;
20
3. // Leap years are divisible by 400 or by 4 but not 100
4. if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 ==
0))){
5. echo "$year is a leap year.";
6. } else{
7. echo "$year is not a leap year.";
8. }
9. ?>
There are two operators which are specifically designed for strings.
The following example will show you these string operators in action:
Example 4.36
1. <?php
2. $x = "Hello";
3. $y = " World!";
4. echo $x . $y; // Outputs: Hello World!
5.
6. $x .= $y;
7. echo $x; // Outputs: Hello World!
8. ?>
The following example will show you these array operators in action:
21
Example 4.37
1. <?php
2. $x = array("a" => "Red", "b" => "Green", "c" => "Blue");
3. $y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
4. $z = $x + $y; // Union of $x and $y
5. var_dump($z);
6. var_dump($x == $y); // Outputs: boolean false
7. var_dump($x === $y); // Outputs: boolean false
8. var_dump($x != $y); // Outputs: boolean true
9. var_dump($x <> $y); // Outputs: boolean true
10. var_dump($x !== $y); // Outputs: boolean true
11. ?>
The date/time functions are used to validate, extract or format the date and time.
The PHP date() function convert a timestamp to a more readable date and time.
The computer stores dates and times in a format called UNIX Timestamp, which measures time
as a number of seconds since the beginning of the Unix epoch (midnight Greenwich Mean Time
on January 1, 1970 i.e. January 1, 1970 00:00:00 GMT ).
Since this is an impractical format for humans to read, PHP converts a timestamp to a format that
is readable to humans and dates from your notation into a timestamp the computer understands.
The syntax of the PHP date() function can be given with.
date(format, timestamp)
The format parameter in the date() function is required which specifies the format of returned
date and time. However the timestamp is an optional parameter, if not included then current date
and time will be used. The following statement displays today's date:
22
Example 4.38
01. <?php
02. $today = date("d/m/Y");
03. echo $today;
04. ?>
Note: The PHP date() function return the current date and time according to the built-in
clock of the web server on which the script has been executed.
The format parameter of the date() function is in fact a string that can contain multiple
characters allowing you to generate a date string containing various components of the date and
time, like day of the week, AM or PM, etc. Here are some of the date-related formatting
characters that are commonly used in format string:
d - Represent day of the month; two digits with leading zeros (01 or 31)
D - Represent day of the week in text as an abbreviation (Mon to Sun)
m - Represent month in numbers with leading zeros (01 or 12)
M - Represent month in text, abbreviated (Jan to Dec)
y - Represent year in two digits (08 or 14)
Y - Represent year in four digits (2008 or 2014)
The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.),
slashes (/), or spaces to add additional visual formatting.
Example 4.39
01. <?php
02. echo date("d/m/Y") . "<br>";
03. echo date("d-m-Y") . "<br>";
04. echo date("d.m.Y");
05. ?>
Tip: You can use the PHP date() function to automatically update the copyright duration on
your website, like: Copyright © 2010-<?php echo date("Y")?>.
Similarly you can use the following characters to format the time string:
23
H - Represent hour in in 24-hour format with leading zeros (00 to 23)
i - Represent minutes with leading zeros (00 to 59)
s - Represent seconds with leading zeros (00 to 59)
a - Represent lowercase ante meridiem and post meridiem (am or pm)
A - Represent uppercase Ante meridiem and Post meridiem (AM or PM)
The PHP code in the following example displays the date in different formats:
Example 4.40
01. <?php
02. echo date("h:i:s") . "<br>";
03. echo date("F d, Y h:i:s A") . "<br>";
04. echo date("h:i a");
05. ?>
The time() function is used to get the current time as a Unix timestamp (the number of seconds
since the beginning of the Unix epoch: January 1 1970 00:00:00 GMT).
Example 4.41
01. <?php
02. // Executed at February 12, 2017, 10:22:10
03. $timestamp = time();
04. echo($timestamp);
05. ?>
1486884116
We can convert this timestamp to a human readable date through passing it to the previously
introduce date() function.
Example 4.42
01. <?php
02. $timestamp = 1394003958;
03. echo(date("F d, Y h:i:s", $timestamp));
04. ?>
24
The above example produces the following output.
The mktime() function is used to create the timestamp based on a specific date and time. If no
date and time is provided, the timestamp for the current date and time is returned.
The following example displays the timestamp corresponding to 3:20:12 pm on May 10, 2014:
Example 4.43
01. <?php
02. // Create the timestamp for a particular date
03. echo mktime(15, 20, 12, 5, 10, 2014);
04. ?>
1399735212
Note: You can leave out as many arguments as you like, and the value corresponding to the
current time will be used instead. If you omit all the arguments, the mktime() function will return
the UNIX timestamp corresponding to the current date and time, just like time().
The maktime() function can be used to find the weekday name corresponding to a particular
date. To do this, simply use the 'l' (lowercase 'L') character with your timestamp, as in the
following example, which displays the day that falls on April 1, 2014:
Example 4.44
01. <?php
02. // Get the weekday name of a particular date
03. echo date('l', mktime(0,0,0,2,12,2017));
04. ?>
Sunday
25
The mktime() function can also be used to find a particular date in future after a specific time
period. As in the following example, which displays the date which falls on after 30 month from
the current date?
Example 4.45
01. <?php
02. // Executed at February 12, 2017
03. $futureDate = mktime(0,0,0,date("m")+30,date("d"),date("Y"));
04. echo date("d/m/Y", $futureDate);
05. ?>
12/08/2019
The PHP superglobal variables $_GET, $_POST and $_REQUEST are used to collect the user inputs
submitted through a form.
In this section, we are going to create a simple HMTL contact form that allows users to enter
their comment and feedback then displays it to the browser using PHP.
Open up your favorite code editor and create a new PHP file. Now type the following code and
save this file as "contact-form.php" in the root directory of your project.
26
<label for="inputName">Name:<sup>*</sup></label>
<input type="text" name="name" id="inputName">
</p>
<p>
<label for="inputEmail">Email:<sup>*</sup></label>
<input type="text" name="email" id="inputEmail">
</p>
<p>
<label for="inputSubject">Subject:</label>
<input type="text" name="subject" id="inputSubject">
</p>
<p>
<label
for="inputComment">Message:<sup>*</sup></label>
<textarea name="message" id="inputComment" rows="5"
cols="30"></textarea>
</p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
11. </form>
12. </body>
13. </html>
Explanation of code
Notice that there are two attributes within the opening <form> tag:
The action attribute references a PHP file "process-form.php" that receives the data entered
into the form when user submit it by pressing the submit button.
The method attribute tells the browser to send the form data through POST method.
The rest of the elements inside the form are basic form controls to receive user inputs.
To learn more about HTML form elements please check out the possible online HTML From
tutorial.
To access the value of a particular form field, you can use the following superglobal variables.
These variables are available in all scopes throughout a script.
27
Superglobal Description
Contains a list of all the field names and values sent by a form using the get method (i.e.
$_GET
via the URL parameters).
Contains a list of all the field names and values sent by a form using the post method
$_POST
(data will not visible in the URL).
Contains the values of both the $_GET and $_POST variables as well as the values of the
$_REQUEST
$_COOKIE superglobal variable.
When a user submit the above contact form through clicking the submit button, the form data is
sent to the "process-form.php" file on the server for processing. It simply captures the
information submitted by the user and displays it to browser.
The PHP code of "process-form.php" file will look something like this:
The PHP code above is quite simple. Since the form data is sent through the post method, you
can retrieve the value of a particular form field by passing its name to the $_POST superglobal
array, and displays each field value using echo() statement.
28
In real world you cannot trust the user inputs; you must implement some sort of validation to
filter the user inputs before using them. In the next section you will learn how to sanitize and
validate this contact form data and send it through the email using PHP.
The PHP filters provide an easy way to sanitize and validate the form data.
As you have seen in the previous section, the process of capturing and displaying the submitted
form data is quite simple. In this section you will learn how to implement a simple contact form
on your website that allows the user to send their comment and feedback through email. We will
use the same PHP mail() function to send the emails.
We are also going to implement some basic security feature like sanitization and validation of
the user's input so that user can not insert potentially harmful data that compromise the website
security or might break the application.
The following is our all-in-one PHP script which does the following things:
It will ask the users to enter his comments about the website.
The same script displays the contact form and process the submitted form data.
The script sanitizes and validates the user inputs. If any required field (marked with *) is
missing or validation failed due to incorrect inputs the script redisplays the form with an
error message for corresponding form field.
The script remembers which fields the user has already filled in, and prefills those fields
when the form redisplayed due to validation error.
If the data submitted by the user are acceptable and everything goes well it will send an
email to the website administrator and display a success message to the user.
Type the following code in "contact.php" file and save in your project root directory:
29
010. return FALSE;
011. }
012. }
013.
014. function filterEmail($field){
015. // Sanitize e-mail address
016. $field = filter_var(trim($field), FILTER_SANITIZE_EMAIL);
017. // Validate e-mail address
018. if(filter_var($field, FILTER_VALIDATE_EMAIL)){
019. return $field;
020. }else{
021. return FALSE;
022. }
023. }
024.
025. function filterString($field){
026. // Sanitize string
027. $field = filter_var(trim($field), FILTER_SANITIZE_STRING);
028. if(!empty($field)){
029. return $field;
030. }else{
031. return FALSE;
032. }
033. }
034. // Define variables and initialize with empty values
035. $nameErr = $emailErr = $messageErr = "";
036. $name = $email = $subject = $message = "";
037. // Processing form data when form is submitted
038. if($_SERVER["REQUEST_METHOD"] == "POST"){
039. // Validate user name
040. if(empty($_POST["name"])){
041. $nameErr = 'Please enter your name.';
042. }else{
043. $name = filterName($_POST["name"]);
044. if($name == FALSE){
045. $nameErr = 'Please enter a valid name.';
046. }
047. }
048. // Validate email address
049. if(empty($_POST["email"])){
050. $emailErr = 'Please enter your email address.';
051. }else{
052. $email = filterEmail($_POST["email"]);
053. if($email == FALSE){
054. $emailErr = 'Please enter a valid email address.';
055. }
056. }
057. // Validate message subject
058. if(empty($_POST["subject"])){
059. $subject = "";
060. }else{
061. $subject = filterString($_POST["subject"]);
062. }
063. // Validate user comment
064. if(empty($_POST["message"])){
065. $messageErr = 'Please enter your comment.';
066. }else{
30
067. $message = filterString($_POST["message"]);
068. if($message == FALSE){
069. $messageErr = 'Please enter a valid comment.';
070. }
071. }
31
0116. </p>
0117. <p>
0118. <label for="inputComment">Message:<sup>*</sup></label>
0119. <textarea name="message" id="inputComment" rows="5"
cols="30"><?php echo $message; ?></textarea>
0120. <span class="error"><?php echo $messageErr; ?></span>
0121. </p>
0122. <input type="submit" value="Send">
0123. <input type="reset" value="Reset">
0124. </form>
0125. </body>
0126. </html>
Explanation of code
You might think what that code was all about. OK, let's get straight into it.
The filterName() function (line no-03) validate input value as person's name. A valid name
can only contain alphabetical characters (a-z, A-Z).
The filterEmail() function (line no-014) validate input value as email address.
The filterString() function (line no-025) only sanitize the input value by stripping HTML
tags and special characters. It doesn't validate the input value against anything.
The attribute action="contact.php" (line no-102) inside the <form> tag specifies that the
same contact.php file display the form as well as process the form data.
The PHP code inside the value attribute of <input> and <textarea> e.g. <?php echo
$name; ?> display prefilled value when form is redisplayed upon validation error.
The PHP code inside the .error class e.g. <span class="error"><?php echo $nameErr;
?></span> display error for corresponding field.
Rest the thing we have already covered in previous chapters. To learn more about sanitize and
validate filters, please check out the online PHP Filter reference.
Note: You need to setup a mail server on your machine for the PHP mail() function to work. If you just
want to implement the form validation you can replace the mail part (line no. 72 to 85) with your own
custom code.
In this section you learn how to use the PHP's error handling functions to deal with the error
conditions gracefully.
Handling Errors
Sometimes your application will not run as it supposed to do, resulting in an error. There are a
number of reasons that may cause errors, for example:
32
The Web server might run out of disk space
A user might have entered an invalid value in a form field
The file or database record that you were trying to access may not exist
The application might not have permission to write to a file on the disk
A service that the application needs to access might be temporarily unavailable
These types of errors are known as runtime errors, because they occur at the time the script runs.
They are distinct from syntax errors that need to be fixed before the script will run. A
professional application must have the capabilities to handle such runtime error gracefully.
Usually this means informing the user about the problem more clearly and precisely.
Usually, when there's a problem that prevents a script from running properly, the PHP engine
triggers an error. Each error is represented by an integer value and an associated constant. The
following table lists some of the common error levels:
Valu
Error Level Description
e
A fatal run-time error, that can't be recovered from. The execution of the
E_ERROR 1
script is stopped immediately.
A run-time warning. It is non-fatal and most errors tend to fall into this
E_WARNING 2
category. The execution of the script is not stopped.
A run-time notice. Indicate that the script encountered something that could
E_NOTICE 8 possibly an error, although the situation could also occur when running a script
normally.
E_STRICT 2048 Not strictly an error, but triggered whenever PHP encounters code that could
33
lead to problems or forward incompatibilities
E_ALL 8191 All errors and warnings, except of E_STRICT prior to PHP 5.4.0.
For more error levels, please check out the online reference on PHP Error Levels.
The PHP engine triggers an error whenever it encounters a problem with your script, but you can
also trigger errors yourself to generate more user friendly error messages. This way you can
make your application more sophisticated. The following section describes some of common
methods used for handling errors in PHP:
Consider the following example that simply tries to open a text file for reading only.
If the file does not exist you might get an error like this:
If we follow some simple steps we can prevent the users from getting such error message.
Example 4.50
01. <?php
02. if(file_exists("sample.txt")){
03. $file = fopen("sample.txt", "r");
04. } else{
05. die("Error: The file you are trying to access doesn't
exist.");
06. }
07. ?>
Now if you run the above script you will get the error message like this:
34
As you can see by implementing a simple check whether the file exist or not before trying to
access it, we can generate an error message that is more meaningful to the user.
The die() function used above simply display the custom error message and terminate the
current script if 'sample.txt' file is not found.
You can create your own error handler function to deal with the run-time error generated by PHP
engine. The custom error handler provides you greater flexibility and better control over the
errors, it can inspect the error and decide what to do with the error, it might display a message to
the user, log the error in a file or database or send by e-mail, attempt to fix the problem and carry
on, exit the execution of the script or ignore the error altogether.
The custom error handler function must be able to handle at least two parameters (errno and
errstr), however it can optionally accept an additional three parameters (errfile, errline, and
errcontext), as described below:
Parameter Description
Specifies the level of the error, as an integer. This corresponds to the appropriate error level
errno
constant ( E_ERROR, E_WARNING, and so on)
errfile Specifies the filename of the script file in which the error occurred, as a string
errline Specifies the line number on which the error occurred, as a string
Specifies an array containing all the variables and their values that existed at the time the
errcontext
error occurred. Useful for debugging
Here's an example of a simple custom error handling function. This handler, customError() is
triggered whenever an error occurred, no matter how trivial. It then outputs the details of the
error to the browser and stops the execution of the script.
Example 4.51
01. <?php
02. // Error handler function
03. function customError($errno, $errstr){
35
04. echo "<b>Error:</b> [$errno] $errstr";
05. }
06. ?>
You need to tell the PHP to use your custom error handler function, just call the built-in
set_error_handler() function, passing in the name of the function.
Example 4.52
01. <?php
02. // Error handler function
03. function customError($errno, $errstr){
04. echo "<b>Error:</b> [$errno] $errstr";
05. }
06.
07. // Set error handler
08. set_error_handler("customError");
09.
010. // Trigger error
011. echo($test);
012. ?>
Error Logging
Log Error Messages in a Text File
You can also logs details of the error to the log file, like this:
Example 4.53
01. <?php
02. function calcDivision($dividend, $divisor){
03. if($divisor == 0){
04. trigger_error("calcDivision(): The divisor cannot be
zero", E_USER_WARNING);
05. return false;
06. } else{
07. return($dividend / $divisor);
08. }
09. }
010. function customError($errno, $errstr, $errfile, $errline,
$errcontext){
011. $message = date("Y-m-d H:i:s - ");
012. $message .= "Error: [" . $errno ."], " . "$errstr in
$errfile on line $errline, ";
013. $message .= "Variables:" . print_r($errcontext, true) .
"\r\n";
014.
015. error_log($message, 3, "logs/app_errors.log");
36
016. die("There was a problem, please try again.");
017. }
018. set_error_handler("customError");
019. echo calcDivision(10, 0);
020. echo "This will never be printed.";
021. ?>
You can also send e-mail with the error details using the same error_log() function.
Example 4.54
01. <?php
02. function calcDivision($dividend, $divisor){
03. if ($divisor == 0){
04. trigger_error("calcDivision(): The divisor cannot be
zero", E_USER_WARNING);
05. return false;
06. } else{
07. return($dividend / $divisor);
08. }
09. }
010. function customError($errno, $errstr, $errfile, $errline,
$errcontext){
011. $message = date("Y-m-d H:i:s - ");
012. $message .= "Error: [" . $errno ."], " . "$errstr in
$errfile on line $errline, ";
013. $message .= "Variables:" . print_r($errcontext, true) .
"\r\n";
014.
015. error_log($message, 1, "[email protected]");
016. die("There was a problem, please try again. Error report
submitted to webmaster.");
017. }
018. set_error_handler("customError");
019. echo calcDivision(10, 0);
020. echo "This will never be printed.";
021. ?>
Trigger an Error
Although the PHP engine triggers an error whenever it encounters a problem with your script,
however you can also trigger errors yourself. This can help to make your application more
robust, because it can flag potential problems before they turn into serious errors.
To trigger an error from within your script, call the trigger_error() function, passing in the
error message that you want to generate:
37
trigger_error("There was a problem.");
Consider the following function that calculates division of the two numbers.
If a value of zero (0) is passed as the $divisor parameter, the error generated by the PHP engine
will look something like this:
This message doesn't look very informative. Consider the following example that uses the
trigger_error() function to generate the error.
As you can see the error message generated by the second example explains the problem more
clearly as compared to the previous one.
38
Chapter 5: PHP DATABASE
5.1 PHP MySQL Introduction
MySQL is the most popular database system used with the PHP language.
What is MySQL
MySQL is one of the most popular relational database systems being used on the Web today. It is
freely available and easy to install, however if you have installed Wampserver it is already there
on your machine. MySQL database server offers several advantages:
MySQL database stores data into tables like other relational database. A table is a collection of
related data, and it is divided into rows and columns.
Each row in a table represents a data record that are inherently connected to each other such as
information related to a particular person, whereas each column represents a specific field such
as 'first_name', 'last_name', 'email_address', etc. The structure of a simple MySQL table that
contains person's general information may look something like this:
+-----------+------------+-----------+----------------------+
+-----------+------------+-----------+----------------------+
39
| 5 | Harry | Potter | [email protected] |
+-----------+------------+-----------+----------------------+
SQL, the Structured Query Language, is a simple, standardized language for communicating
with relational databases like MySQL. With SQL you can perform any database-related task,
such as creating databases and tables, saving data in database tables, query a database for
specific records, deleting and updating data in databases.
Look at the following standard SQL query that returns the email address of a person whose first
name is equal to 'Peter' in the persons table:
If you execute the SQL query above it will return the following record:
In order to access the data inside a MySQL database, you first need to open a connection to the
MySQL database server. In PHP you can easily do this using the mysqli_connect() function.
All communication between PHP and the MySQL database server takes place through this
connection. The basic syntax of the mysqli_connect() function is given with:
Parameter Description
40
Parameter Description
Example 5.1
1. <?php
2. /* Attempt MySQL server connection. Assuming you are running MySQL
3. server with default setting (user 'root' with no password) */
4. $link = mysqli_connect("localhost", "root", "");
5. // Check connection
6. if($link === false){
7. die("ERROR: Could not connect. " . mysqli_connect_error());
8. }
9. ?>
Note: The default username for MySQL database server is 'root' and there is no password.
However to prevent your databases from intrusion and unauthorized access you should set
password for MySQL accounts.
The connection to the MySQL database server will be closed automatically as soon as the
execution of the script ends. However, if you want to close it earlier you can do this by simply
calling the PHP mysql_close() function.
Example 5.2
01. <?php
02. /* Attempt MySQL server connection. Assuming you are running
MySQL
03. server with default setting (user 'root' with no password) */
04. $link = mysqli_connect("localhost", "root", "");
05. // Check connection
06. if($link === false){
07. die("ERROR: Could not connect. " . mysqli_connect_error());
08. }
09. // Close connection
010. mysqli_close($link);
011. ?>
41
5.3 PHP MySQL Create Database and Tables
The CREATE DATABASE and CREATE TABLE statement is used to create MySQL database
and table respectively.
Now you have understood how to open a connection to the MySQL database server. In this
section you will learn how to execute SQL query to create a database and tables.
Since all tables are stored in a database, so first we have to create a database before creating
tables. The CREATE DATABASE statement is used to create a database in MySQL.
Let's make a SQL query using the CREATE DATABASE statement, after that we will execute this
SQL query through passing it to the mysqli_query() function to finally create our database.
The following example creates a database named "demo".
Example 5.3
1. <?php
2. /* Attempt MySQL server connection. Assuming you are running MySQL
3. server with default setting (user 'root' with no password) */
4. $link = mysqli_connect("localhost", "root", "");
5.
6. // Check connection
7. if($link === false){
8. die("ERROR: Could not connect. " . mysqli_connect_error());
9. }
10.
11. // Attempt create database query execution
12. $sql = "CREATE DATABASE demo";
13. if(mysqli_query($link, $sql)){
14. echo "Database demo created successfully";
15. } else{
16. echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
17. }
18.
19. // Close connection
20. mysqli_close($link);
21. ?>
42
Adding Tables to MySQL Database
Since our database is created now it's time to add some tables to it. The CREATE TABLE statement
is used to create a table in MySQL database.
So let's make a SQL query using the CREATE TABLE statement, after that we will execute this
SQL query through passing it to the mysqli_query() function to finally create our table.
Example 5.4
1. <?php
2. /* Attempt MySQL server connection. Assuming you are running MySQL
3. server with default setting (user 'root' with no password) */
4. $link = mysqli_connect("localhost", "root", "", "demo");
5.
6. // Check connection
7. if($link === false){
8. die("ERROR: Could not connect. " . mysqli_connect_error());
9. }
10.
11. // Attempt create table query execution
12. $sql = "CREATE TABLE persons(person_id INT NOT NULL PRIMARY
KEY AUTO_INCREMENT, first_name VARCHAR(30) NOT NULL, last_name
VARCHAR(30) NOT NULL, email_address VARCHAR(70))";
13. if (mysqli_query($link, $sql)){
14. echo "Table persons created successfully";
15. } else {
16. echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
17. }
18.
19. // Close connection
20. mysqli_close($link);
21. ?>
The PHP code in the above example creates a table named persons which has four fields
'person_id', 'first_name', 'last_name' and 'email_address'. Notice that each field name is followed
by a data type declaration; this declaration identifies what type of data the field can hold,
whether string, numeric, temporal, or Boolean. MySQL supports a number of different data
types, the most important ones are summarized below.
43
Data Type Description
Stores timestamp values. TIMESTAMP values are stored as the number of seconds since the
TIMESTAMP
Unix epoch ('1970-01-01 00:00:01' UTC).
Please check out the online reference on MySQL data types for the detailed information on all
the data types available in MySQL database system.
There are a few additional modifiers that are specified after the fields in the preceding SQL
statement like: NOT NULL, PRIMARY KEY, AUTO_INCREMENT. It has the following
meaning
The NOT NULL modifier definition specifies that the field cannot accept a NULL value.
The PRIMARY KEY modifier marks the corresponding field as the table's primary key
which is used to uniquely identify the rows in a table. Each table in a relational database
should have a primary key field.
The AUTO_INCREMENT modifier tells MySQL to automatically generate a value for
this field every time a new record is inserted into the table, by incrementing the previous
value by 1. Only available for numeric fields.
In the upcoming sections you will learn how to insert new records as well as how to update,
delete and view the existing records of persons table inside the demo database.
Now you've understood how to create database and tables in MySQL. In this section you will
learn how to execute SQL query to insert records in a table.
44
Let's make a SQL query using the INSERT INTO statement with appropriate values, after that we
will execute this SQL query through passing it to the mysqli_query() function to insert data in
table. Here's an example, which adds a record to the persons table by specifying values for the
'person_id', 'first_name', 'last_name' and 'email_address' fields:
Example 5.5
1. <?php
2. /* Attempt MySQL server connection. Assuming you are running
MySQL
3. server with default setting (user 'root' with no password) */
4. $link = mysqli_connect("localhost", "root", "", "demo");
5.
6. // Check connection
7. if($link === false){
8. die("ERROR: Could not connect. " . mysqli_connect_error());
9. }
10. // Attempt insert query execution
11. $sql = "INSERT INTO persons (person_id, first_name, last_name,
email_address) VALUES (1, 'Peter', 'Parker',
'[email protected]')";
12. if(mysqli_query($link, $sql)){
13. echo "Records added successfully.";
14. } else{
15. echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
16. }
17.
18. // Close connection
19. mysqli_close($link);
20. ?>
If you remember, from the preceding section, the 'person_id' field was marked with the
AUTO_INCREMENT flag. This modifier tells the MySQL to automatically assign a value to this
field if it is left unspecified while inserting a new record to the persons table. To see this in
action, try adding another record using the following statement:
Example 5.6
1. <?php
2. /* Attempt MySQL server connection. Assuming you are running MySQL
3. server with default setting (user 'root' with no password) */
4. $link = mysqli_connect("localhost", "root", "", "demo");
5.
6. // Check connection
7. if($link === false){
8. die("ERROR: Could not connect. " . mysqli_connect_error());
45
9. }
10.
11. // Attempt insert query execution
12. $sql = "INSERT INTO persons (first_name, last_name,
email_address) VALUES ('John', 'Rambo', '[email protected]')";
13. if(mysqli_query($link, $sql)){
14. echo "Records added successfully.";
15. } else{
16. echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
17. }
18.
19. // Close connection
20. mysqli_close($link);
21. ?>
Now go the phpMyAdmin (http://localhost/phpmyadmin/) and check out the persons table
data inside the demo database, you will see the new 'person_id' is assigned automatically by
incrementing the value of previous 'person_id' by 1.
Let's create an HTML form that can be used to insert new records to persons table.
Here's a simple HTML form that has three text <input> fields and a submit button.
Example 5.7
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>Add Record Form</title>
6. </head>
7. <body>
8. <form action="insert.php" method="post">
9. <p>
<label for="firstName">First Name:</label>
<input type="text" name="firstname" id="firstName">
10. </p>
11. <p>
<label for="lastName">Last Name:</label>
<input type="text" name="lastname" id="lastName">
12. </p>
13. <p>
46
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
14. </p>
15. <input type="submit" value="Submit">
16. </form>
17. </body>
18. </html>
When a user clicks the submit button of the add record HTML form, in the example above, the
form data is sent to 'insert.php' file. The 'insert.php' file connects to the MySQL database
server, retrieves forms fields using the PHP $_POST variables and finally execute the insert query
to add the records. Here is the complete code of our 'insert.php' file:
47
26. ?>
This is very basic example of inserting the form data in a MySQL database table. You can extend
this example and make it more interactive by adding validations to the user inputs before
inserting it to the database tables. Please refer to the section in Part III on PHP form validation
to learn more about sanitizing and validating user inputs using PHP.
SELECT statement is used to select the records from MySQL database tables.
So far you have learnt how to create database and table as well as inserting data. Now it's time to
retrieve data what have inserted in the preceding section.
Let's make a SQL query using the SELECT statement, after that we will execute this SQL query
through passing it to the mysqli_query() function to retrieve the table data.
+-----------+------------+-----------+----------------------+
| person_id | first_name | last_name | email_address |
+-----------+------------+-----------+----------------------+
| 1 | Peter | Parker | [email protected] |
| 2 | John | Rambo | [email protected] |
| 3 | Clark | Kent | [email protected] |
| 4 | John | Carter | [email protected] |
| 5 | Harry | Potter | [email protected] |
+-----------+------------+-----------+----------------------+
The PHP code in the following example selects all the data stored in the "persons" table (using
the asterisk character (*) in place of column name selects all the data in the table).
Example 5.9
1. <?php
2. /* Attempt MySQL server connection. Assuming you are running MySQL
3. server with default setting (user 'root' with no password) */
48
4. $link = mysqli_connect("localhost", "root", "", "demo");
5.
6. // Check connection
7. if($link === false){
8. die("ERROR: Could not connect. " . mysqli_connect_error());
9. }
10.
11. // Attempt select query execution
12. $sql = "SELECT * FROM persons";
13. if($result = mysqli_query($link, $sql)){
14. if(mysqli_num_rows($result) > 0){
15. echo "<table>";
16. echo "<tr>";
17. echo "<th>person_id</th>";
18. echo "<th>first_name</th>";
19. echo "<th>last_name</th>";
20. echo "<th>email_address</th>";
21. echo "</tr>";
22. while($row = mysqli_fetch_array($result)){
23. echo "<tr>";
24. echo "<td>" . $row['person_id'] . "</td>";
25. echo "<td>" . $row['first_name'] . "</td>";
26. echo "<td>" . $row['last_name'] . "</td>";
27. echo "<td>" . $row['email_address'] . "</td>";
28. echo "</tr>";
29. }
30. echo "</table>";
31. // Close result set
32. mysqli_free_result($result);
33. } else{
34. echo "No records matching your query were found.";
35. }
36. } else{
37. echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
38. }
39.
40. // Close connection
41. mysqli_close($link);
42. ?>
In the example above, the data returned by the mysqli_query() function is stored in the
$result variable. Each time mysqli_fetch_array() is invoked, it returns the next record from
the result set as an array. The while loop is used to loop through all the records in the result set.
Finally the value of individual fields can be accessed from the record either through passing the
field index or the field name to the $row variable like $row['person_id'] or $row[0],
$row['first_name'] or $row[1], $row['last_name'] or $row[2], and
$row['email_address'] or $row[3].
49
If you want to use the for loop you can obtain the loop counter value or the number of rows
returned by the query by passing the $result variable to the mysqli_num_rows() function. This
loop counter value determines how many times the loop should run.
A WHERE clause filters the records according to the condition in the clause.
The WHERE clause is used to extract only those records that fulfill a specified condition.
Let's make a SQL query using the WHERE clause in SELECT statement, after that we'll execute this
SQL query through passing it to the mysqli_query() function to get the filtered data.
+-----------+------------+-----------+----------------------+
| person_id | first_name | last_name | email_address |
+-----------+------------+-----------+----------------------+
| 1 | Peter | Parker | [email protected] |
| 2 | John | Rambo | [email protected] |
| 3 | Clark | Kent | [email protected] |
| 4 | John | Carter | [email protected] |
| 5 | Harry | Potter | [email protected] |
+-----------+------------+-----------+----------------------+
The following PHP code selects all the rows from the persons table where first_name='john':
Example 5.10
1. <?php
2. /* Attempt MySQL server connection. Assuming you are running MySQL
3. server with default setting (user 'root' with no password) */
4. $link = mysqli_connect("localhost", "root", "", "demo");
5.
6. // Check connection
7. if($link === false){
8. die("ERROR: Could not connect. " . mysqli_connect_error());
9. }
10.
11. // Attempt select query execution
12. $sql = "SELECT * FROM persons WHERE first_name='john'";
50
13. if($result = mysqli_query($link, $sql)){
14. if(mysqli_num_rows($result) > 0){
15. echo "<table>";
16. echo "<tr>";
17. echo "<th>person_id</th>";
18. echo "<th>first_name</th>";
19. echo "<th>last_name</th>";
20. echo "<th>email_address</th>";
21. echo "</tr>";
22. while($row = mysqli_fetch_array($result)){
23. echo "<tr>";
24. echo "<td>" . $row['person_id'] . "</td>";
25. echo "<td>" . $row['first_name'] . "</td>";
26. echo "<td>" . $row['last_name'] . "</td>";
27. echo "<td>" . $row['email_address'] . "</td>";
28. echo "</tr>";
29. }
30. echo "</table>";
31. // Close result set
32. mysqli_free_result($result);
33. } else{
34. echo "No records matching your query were found.";
35. }
36. } else{
37. echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
38. }
39.
40. // Close connection
41. mysqli_close($link);
42. ?>
After filtration the result set will look something like this:
+-----------+------------+-----------+---------------------+
| person_id | first_name | last_name | email_address |
+-----------+------------+-----------+---------------------+
| 2 | John | Rambo | [email protected] |
| 4 | John | Carter | [email protected] |
51
Updating Database Table Data
The UPDATE statement is used to change or modify the existing records in a database table. It is
typically used in conjugation with the WHERE clause to apply the changes to only those records
that matches specific criteria.
WHERE column_name=some_value
Let's make a SQL query using the UPDATE statement and WHERE clause, after that we will execute
this SQL query through passing it to the mysqli_query() function to update the tables records.
Consider the following "persons" table inside the "demo" database:
+-----------+------------+-----------+----------------------+
| person_id | first_name | last_name | email_address |
+-----------+------------+-----------+----------------------+
| 1 | Peter | Parker | [email protected] |
| 2 | John | Rambo | [email protected] |
| 3 | Clark | Kent | [email protected] |
| 4 | John | Carter | [email protected] |
| 5 | Harry | Potter | [email protected] |
+-----------+------------+-----------+----------------------+
The PHP code in the following example update the email address of a person in the persons table
whose first_name='Peter' and last_name='Parker'.
Example 5.12
1. <?php
2. /* Attempt MySQL server connection. Assuming you are running MySQL
3. server with default setting (user 'root' with no password) */
4. $link = mysqli_connect("localhost", "root", "", "demo");
5.
6. // Check connection
7. if($link === false){
8. die("ERROR: Could not connect. " . mysqli_connect_error());
9. }
10.
11. // Attempt update query execution
12. $sql = "UPDATE persons SET
email_address='[email protected]' WHERE first_name='Peter'
AND last_name='Parker'";
13. if(mysqli_query($link, $sql)){
14. echo "Records were updated successfully.";
52
15. } else {
16. echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
17. }
18.
19. // Close connection
20. mysqli_close($link);
21. ?>
After update the persons table will look something like this:
+-----------+------------+-----------+--------------------------+
| person_id | first_name | last_name | email_address |
+-----------+------------+-----------+--------------------------+
| 1 | Peter | Parker | [email protected] |
| 2 | John | Rambo | [email protected] |
| 3 | Clark | Kent | [email protected] |
| 4 | John | Carter | [email protected] |
| 5 | Harry | Potter | [email protected] |
+-----------+------------+-----------+--------------------------+
Warning: The WHERE clause in the UPDATE statement specifies which record or records should be
updated. If you omit the WHERE clause, all records will be updated.
DELETE statement is used to delete the records from a MySQL database table.
Just as you insert records into tables, you can delete records from a table using the DELETE
statement. It is typically used in conjugation with the WHERE clause to delete only those records
that matches specific criteria or condition.
Let's make a SQL query using the DELETE statement and WHERE clause, after that we will execute
this SQL query through passing it to the mysqli_query() function to delete the tables records.
Consider the following "persons" table inside the "demo" database:
+-----------+------------+-----------+----------------------+
+-----------+------------+-----------+----------------------+
53
| 1 | Peter | Parker | [email protected] |
+-----------+------------+-----------+----------------------+
The PHP code in the following example deletes all the records of persons from the above persons
table whose first_name='John'.
Example 5.13
1. <?php
2. /* Attempt MySQL server connection. Assuming you are running MySQL
3. server with default setting (user 'root' with no password) */
4. $link = mysqli_connect("localhost", "root", "", "demo");
5.
6. // Check connection
7. if($link === false){
8. die("ERROR: Could not connect. " . mysqli_connect_error());
9. }
10.
11. // Attempt delete query execution
12. $sql = "DELETE FROM persons WHERE first_name='John'";
13. if(mysqli_query($link, $sql)){
14. echo "Records were deleted successfully.";
15. } else{
16. echo "ERROR: Could not able to execute $sql. " .
mysqli_error($link);
17. }
18.
19. // Close connection
20. mysqli_close($link);
21. ?>
After the deletion the persons table will look something like this:
+-----------+------------+-----------+----------------------+
+-----------+------------+-----------+----------------------+
54
| 3 | Clark | Kent | [email protected] |
+-----------+------------+-----------+----------------------+
As you can see the records has been deleted successfully from the persons table.
Warning: The WHERE clause in the DELETE statement specifies which record or records should be
deleted. If you omit the WHERE clause, all records will be deleted.
55