Advanced PHP Manual
Advanced PHP Manual
Advanced PHP Manual
PHP Date and Time
In this tutorial you will learn how to extract or format the date and time in PHP.
The PHP Date() Function
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)
Example
Run this code »
<?php
$today=date("d/m/Y");
echo$today;
?>
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.
Formatting the Dates and Times with PHP
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 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)
L- represent the day of the week in full (Monday to Sunday)
F- represent month in text(January to December)
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
Run this code »
<?php
echodate("d/m/Y")."<br>";
echodate("d-m-Y")."<br>";
echodate("d.m.Y");
?>
Similarly you can use the following characters to format the time string:
The PHP code in the following example displays the date in different formats:
Example
Run this code »
<?php
echodate("h:i:s")."<br>";
echodate("F d, Y h:i:s A")."<br>";
echodate("h:i a");
?>
The PHP time() Function
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
Run this code »
<?php
// Executed at March 05, 2014 07:19:18
$timestamp=time();
echo($timestamp);
?>
1394003958
We can convert this timestamp to a human readable date through passing it to
the previously introduce date() function.
Example
Run this code »
<?php
$timestamp=1394003958;
echo(date("F d, Y h:i:s",$timestamp));
?>
The PHP mktime() Function
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.
Example
Run this code »
<?php
// Create the timestamp for a particular date
echo mktime(15,20,12,5,10,2014);
?>
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().
Example
Run this code »
<?php
// Get the weekday name of a particular date
echo date('l',mktime(0,0,0,4,1,2014));
?>
Tuesday
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
Run this code »
<?php
// Executed at March 05, 2014
$futureDate=mktime(0,0,0,date("m")+30,date("d"),date("Y"));
echodate("d/m/Y",$futureDate);
?>
05/09/2016
PHP Include and Require Files
In this tutorial you will learn how to include and evaluate the files in PHP.
You can save a lot of time and work through including files — Just store a block
of code in a separate file and include it wherever you want using
the include() and require() statements instead of typing the entire block of
code multiple times. A typical example is including the header, footer and menu
file within all the pages of a website.
The following example will show you how to include the common header, footer
and menu codes which are stored in separate 'header.php', 'footer.php' and
'menu.php' files respectively, within all the pages of your website. Using this
technique you can update all pages of the website at once by making the
changes to just one file, this saves a lot of repetitive work.
Example
Run this code »
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tutorial Republic</title>
</head>
<body>
<?phpinclude"header.php";?>
<?phpinclude"menu.php";?>
<h1>Welcome to Our Website!</h1>
<p>Here you will find lots of useful information.</p>
<?phpinclude"footer.php";?>
</body>
</html>
Example
Run this code »
<?phprequire"my_variables.php";?>
<?phprequire"my_functions.php";?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?phpdisplayTitle($home_page);?></title>
</head>
<body>
<?phpinclude"header.php";?>
<?phpinclude"menu.php";?>
<h1>Welcome to Our Website!</h1>
<p>Here you will find lots of useful information.</p>
<?phpinclude"footer.php";?>
</body>
</html>
Tip: It is recommended to use the require() statement if you're including the
library files or files containing the functions and configuration variables that are
essential for running your application, such as database configuration file.
Example
Run this code »
<?php
functionmultiplySelf($var){
$var*=$var;// multiply variable by itself
echo$var;
}
?>
Here's is the PHP script within which we've included the 'my_functions.php' file.
Example
Run this code »
<?php
// Including file
require"my_functions.php";
// Calling the function
multiplySelf(2);// Output: 4
echo"<br>";
Example
Run this code »
<?php
// Including file
require_once"my_functions.php";
// Calling the function
multiplySelf(2);// Output: 4
echo"<br>";
PHP File System
In this tutorial you will learn how to create, access (or read) and manipulate files
dynamically using the PHP's file system functions.
The first parameter passed to fopen() specifies the name of the file you want to
open, and the second parameter specifies in which mode the file should be
opened. For example:
Example
Run this code »
<?php
$handle=fopen("data.txt","r");
?>
The file may be opened in one of the following modes:
w Open the file for writing only and clears the contents of file. If the
file does not exist, PHP will attempt to create it.
w+ Open the file for reading and writing and clears the contents of
file. If the file does not exist, PHP will attempt to create it.
a Append. Opens the file for writing only. Preserves file content by
writing to the end of the file. If the file does not exist, PHP will
attempt to create it.
x+ Open the file for reading and writing; otherwise it has the same
behavior as 'x'.
If you try to open a file that doesn't exist, PHP will generate a warning message.
So, to avoid these error messages you should always implement a simple check
whether a file or directory exists or not before trying to access it, with the
PHP file_exists() function.
Example
Run this code »
<?php
$file="data.txt";
Example
Run this code »
<?php
$file="data.txt";
This function takes two parameter — A file handle and the number of bytes to
read. The following example reads 20 bytes from the "data.txt" file including
spaces. Let's suppose the file "data.txt" contains a paragraph of text "The quick
brown fox jumps over the lazy dog."
Example
Run this code »
<?php
$file="data.txt";
Example
Run this code »
<?php
$file="data.txt";
The easiest way to read the entire contents of a file in PHP is with
the readfile() function. This function allows you to read the contents of a file
without needing to open it. The following example will generate the same output
as above example:
Example
Run this code »
<?php
$file="data.txt";
Another way to read the whole contents of a file without needing to open it is
with the file_get_contents() function. This function accepts the name and path
to a file, and reads the entire file into a string variable. Here's an example:
Example
<?php
$file="data.txt";
To process the file data, you need to iterate over the array using a foreach loop.
Here's an example, which reads a file into an array and then displays it using the
loop:
Example
Run this code »
<?php
$file="data.txt";
Example
Run this code »
<?php
$file="note.txt";
Example
Run this code »
<?php
$file="note.txt";
Example
Run this code »
<?php
$file="note.txt";
<?php
$file="file.txt";
Example
Run this code »
<?php
$file="note.txt";
Function Description
Please check out the PHP filesystem reference for other useful PHP filesystem
functions.
Chapter 21
PHP Parsing Directories
In this tutorial you will learn how to process directories or folders using PHP.
Example
Run this code »
<?php
// The directory path
$dir="testdir";
Example
Run this code »
<?php
// Source file path
$file="example.txt";
Now we're going to create a custom function that will recursively list all files in a
directory using PHP. This script will be helpful if you're working with deeply
nested directory structure.
Example
Run this code »
<?php
// Define a function to output files in a directory
functionoutputFiles($path){
// Check directory exists or not
if(file_exists($path)&& is_dir($path)){
// Scan the files in this directory
$result=scandir($path);
if(count($files)>0){
// Loop through retuned array
foreach($filesas$file){
if(is_file("$path/$file")){
// Display filename
echo$file."<br>";
}elseif(is_dir("$path/$file")){
// Recursively call the function if directories found
outputFiles("$path/$file");
}
}
}else{
echo"ERROR: No files found in the directory.";
}
}else{
echo"ERROR: The directory does not exist.";
}
}
// Call the function
outputFiles("mydir");
?>
The PHP code in the following example will search the documents directory and
list all the files with .text extension. It will not search the subdirectories.
Example
Run this code »
<?php
/* Search the directory and loop through
returned array containing the matched files */
foreach(glob("documents/*.txt")as$file){
echobasename($file)." (size: ".filesize($file)." bytes)"."<br>";
}
?>
The glob() function can also be used to find all the files within a directory or its
subdirectories. The function defined in the following example will recursively list
all files within a directory, just like we've done in previous example with
the scandir() function.
Example
Run this code »
<?php
// Define a function to output files in a directory
functionoutputFiles($path){
// Check directory exists or not
if(file_exists($path)&&is_dir($path)){
// Search the files in this directory
$files=glob($path."/*");
if(count($files)>0){
// Loop through retuned array
foreach($filesas$file){
if(is_file("$file")){
// Display only filename
echobasename($file)."<br>";
}elseif(is_dir("$file")){
// Recursively call the function if directories found
outputFiles("$file");
}
}
}else{
echo"ERROR: No such file found in the directory.";
}
}else{
echo"ERROR: The directory does not exist.";
}
}
PHP File Upload
In this tutorial you'll learn how to upload a file to the remote web server with
PHP.
Example
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload Form</title>
</head>
<body>
<form action="upload-
manager.php"method="post"enctype="multipart/form-data">
<h2>Upload File</h2>
<label for="fileSelect">Filename:</label>
<input type="file"name="photo"id="fileSelect">
<input type="submit"name="submit"value="Upload">
<p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats
allowed to a max size of 5 MB.</p>
</form>
</body>
</html>
Example
Download
<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"]=="POST"){
// Check if file was uploaded without errors
if(isset($_FILES["photo"])&&$_FILES["photo"]["error"]==0){
$allowed=array("jpg"=>"image/jpg","jpeg"=>"image/jpeg","gif"=>"im
age/gif","png"=>"image/png");
$filename=$_FILES["photo"]["name"];
$filetype=$_FILES["photo"]["type"];
$filesize=$_FILES["photo"]["size"];
Note: The above script prevents uploading a file with the same name as an
existing file in the same folder. However, if you want to allow this just prepend
the file name with a random string or timestamp, like $filename = time() . '_' .
$_FILES["photo"]["name"];
You might be wondering what this code was all about. Well, let's go through
each part of this example code one by one for a better understanding of this
process.
Explanation of Code
Once the form is submitted information about the uploaded file can be accessed
via PHP superglobal array called $_FILES. For example, our upload form contains a
file select field called photo (i.e. name="photo"), if any user uploaded a file using this
field, we can obtains its details like the name, type, size, temporary name or any
error occurred while attempting the upload via the $_FILES["photo"] associative
array, like this:
The PHP code in the following example will simply display the details of the
uploaded file and stores it in a temporary directory on the web server.
Example
Download
<?php
if($_FILES["photo"]["error"]>0){
echo"Error: ".$_FILES["photo"]["error"]."<br>";
}else{
echo"File Name: ".$_FILES["photo"]["name"]."<br>";
echo"File Type: ".$_FILES["photo"]["type"]."<br>";
echo"File Size: ".($_FILES["photo"]["size"]/1024)." KB<br>";
echo"Stored in: ".$_FILES["photo"]["tmp_name"];
}
?>
Tip: Once a file has been successfully uploaded, it is automatically stored in a
temporary directory on the server. To store this file on a permanent basis, you
need to move it from the temporary directory to a permanent location using the
PHP's move_uploaded_file() function.
Chapter 23
PHP File Download
In this tutorial you will learn how to force download a file using PHP.
Example
Try this code »
Let's create a file named "image-gallery.php" and place the following code inside
it.
Example
Run this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Image Gallery</title>
<style type="text/css">
.img-box{
display: inline-block;
text-align: center;
margin: 0 15px;
}
</style>
</head>
<body>
<?php
// Array containing sample image file names
$images=array("kites.jpg","balloons.jpg");
Here's the complete code of "download.php" file, which force image download.
Example
Run this code »
<?php
if(isset($_REQUEST["file"])){
// Get parameters
$file=urldecode($_REQUEST["file"]);// Decode URL-encoded string
// Process download
if(file_exists($filepath)){
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;
filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: '.filesize($filepath));
flush();// Flush system output buffer
readfile($filepath);
die();
}else{
http_response_code(404);
die();
}
}else{
die("Invalid file name!");
}
}
?>
Similarly, you can force download other files formats like word doc, pdf files, etc.
The regular expression in the above example (line no-8) will simply not allow
those files whose name starts or ends with a dot character (.), for example, it
allows the file names such as kites.jpg or Kites.jpg, myscript.min.js but do not
allow kites.jpg. or .kites.jpg.
Please check out the tutorial on regular expressions to learn the regular
expressions in details.
Chapter 24
PHP Cookies
In this tutorial you will learn how to store a small amount of information within
the user's browser itself using the PHP cookies.
What is a Cookie
A cookie is a small text file that lets you store a small amount of data (nearly 4KB)
on the user's computer. They are typically used to keeping track of information
such as username that the site can retrieve to personalize the page when user
visit the website next time.
Tip: Each time the browser requests a page to the server, all the data in the
cookie is automatically sent to the server within the request.
Paramete Description
r
expires The expiry date in UNIX timestamp format. After this time
cookie will become inaccessible. The default value is 0.
path Specify the path on the server for which the cookie will be
available. If set to /, the cookie will be available within the
entire domain.
domain Specify the domain for which the cookie is available to e.g
www.example.com.
secure This field, if present, indicates that the cookie should be sent
only if a secure HTTPS connection exists.
Tip: If the expiration time of the cookie is set to 0, or omitted, the cookie will
expire at the end of the session i.e. when the browser closes.
Example
Download
<?php
// Setting a cookie
setcookie("username","John Carter",time()+30*24*60*60);
?>
Note: All the arguments except the name are optional. You may also replace an
argument with an empty string ("") in order to skip that argument, however to
skip the expire argument use a zero (0) instead, since it is an integer.
Example
<?php
// Accessing an individual cookie value
echo $_COOKIE["username"];
?>
The PHP code in the above example produce the following output.
John Carter
It's a good practice to check whether a cookie is set or not before accessing its
value. To do this you can use the PHP isset() function, like this:
Example
Download
<?php
// Verifying whether a cookie is set or not
if(isset($_COOKIE["username"])){
echo"Hi ".$_COOKIE["username"];
}else{
echo"Welcome Guest!";
}
?>
You can use the print_r() function like print_r($_COOKIE); to see the structure of
this $_COOKIE associative array, like you with other arrays.
Removing Cookies
You can delete a cookie by calling the same setcookie() function with the cookie
name and any value (such as an empty string) however this time you need the set
the expiration date in the past, as shown in the example below:
Example
Download
<?php
// Deleting a cookie
setcookie("username","",time()-3600);
?>
Tip: You should pass exactly the same path, domain, and other arguments that
you have used when you first created the cookie in order to ensure that the
correct cookie is deleted.
Chapter 25
PHP Sessions
In this tutorial you will learn how to store certain data on the server on a
temporary basis using PHP session.
What is a Session
Although you can store data using cookies but it has some security issues. Since
cookies are stored on user's computer it is possible for an attacker to easily
modify a cookie content to insert potentially harmful data in your application that
might break your application.
Also every time the browser requests a URL to the server, all the cookie data for a
website is automatically sent to the server within the request. It means if you have
stored 5 cookies on user's system, each having 4KB in size, the browser needs to
upload 20KB of data each time the user views a page, which can affect your site's
performance.
You can solve both of these issues by using the PHP session. A PHP session stores
data on the server rather than user's computer. In a session based environment,
every user is identified through a unique number called session identifier or SID.
This unique session ID is used to link each user with their own information on the
server like emails, posts, etc.
Tip: The session IDs are randomly generated by the PHP engine which is almost
impossible to guess. Furthermore, because the session data is stored on the
server, it doesn't have to be sent with every browser request.
The PHP code in the example below simply starts a new session.
Example
Download
<?php
// Starting session
session_start();
?>
The session_start() function first checks to see if a session already exists by
looking for the presence of a session ID. If it finds one, i.e. if the session is already
started, it sets up the session variables and if doesn't, it starts a new session by
creating a new session ID.
Example
Download
<?php
// Starting session
session_start();
Example
Download
<?php
// Starting session
session_start();
Note: To access the session data in the same page there is no need to recreate
the session since it has been already started on the top of the page.
Destroying a Session
If you want to remove certain session data, simply unset the corresponding key
of the $_SESSION associative array, as shown in the following example:
Example
Download
<?php
// Starting session
session_start();
Example
Download
<?php
// Starting session
session_start();
// Destroying session
session_destroy();
?>
Note: Before destroying a session with the session_destroy() function, you need to
first recreate the session environment if it is not already there using
the session_start() function, so that there is something to destroy.
PHP Send Emails
In this tutorial you will learn how to send simple text or HTML emails directly
from the script using the PHP mail() function.
The PHP mail() Function
Sending email messages are very common for a web application, for example,
sending welcome email when a user create an account on your website, sending
newsletters to your registered users, or getting user feedback or comment
through website's contact form, and so on.
You can use the PHP built-in mail() function for creating and sending email
messages to one or more recipients dynamically from your PHP application either
in a plain-text form or formatted HTML. The basic syntax of this function can be
given with:
mail(to, subject, message, headers, parameters)
Parameter Description
exceed 70 characters.
Example
Download
<?php
$to='[email protected]';
$subject='Marriage Proposal';
$message='Hi Jane, will you marry me?';
$from='[email protected]';
// Sending email
if(mail($to,$subject,$message)){
echo'Your mail has been sent successfully.';
}else{
echo'Unable to send email. Please try again.';
}
?>
Sending HTML Formatted Emails
When you send a text message using PHP, all the content will be treated as
simple text. We're going to improve that output, and make the email into a
HTML-formatted email.
To send an HTML email, the process will be the same. However, this time we need
to provide additional headers as well as an HTML formatted message.
Example
Download
<?php
$to='[email protected]';
$subject='Marriage Proposal';
$from='[email protected]';
// Sending email
if(mail($to,$subject,$message,$headers)){
echo'Your mail has been sent successfully.';
}else{
echo'Unable to send email. Please try again.';
}
?>
Note: However, the PHP mail() function is a part of the PHP core but you need to
set up a mail server on your machine to make it really work.
In the next two chapters (PHP Form Handling and PHP Form Validation) you will
learn how to implement an interactive contact form on your website to receive
the user's comment and feedback through emails using this PHP send mail
feature.
Chapter 27
PHP Form Handling
In this tutorial you'll learn how to collect user inputs submitted through a form
using the PHP superglobal variables $_GET, $_POST and $_REQUEST.
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.
Example
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
</head>
<body>
<h2>Contact Us</h2>
<p>Please fill in this form and send us.</p>
<form action="process-form.php"method="post">
<p>
<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">
</form>
</body>
</html>
Explanation of code
Notice that there are two attributes within the opening <form> tag:
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 HTML
Forms tutorial.
The PHP code of "process-form.php" file will look something like this:
Example
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
</head>
<body>
<h1>Thank You</h1>
<p>Here is the information you have submitted:</p>
<ol>
<li><em>Name:</em><?phpecho$_POST["name"]?></li>
<li><em>Email:</em><?phpecho$_POST["email"]?></li>
<li><em>Subject:</em><?phpecho$_POST["subject"]?></li>
<li><em>Message:</em><?phpecho$_POST["message"]?></li>
</ol>
</body>
</html>
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.
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 chapter you will
learn how sanitize and validate this contact form data and send it through the
email using PHP.
Chapter 28
PHP Form Validation
In this tutorial you'll learn how to sanitize and validate form data using PHP
filters.
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:
Example
Download
<?php
// Functions to filter user inputs
functionfilterName($field){
// Sanitize user name
$field=filter_var(trim($field),FILTER_SANITIZE_STRING);
// Sending email
if(mail($to,$subject,$message,$headers)){
echo'<p class="success">Your message has been sent successfully!
</p>';
}else{
echo'<p class="error">Unable to send email. Please try again!
</p>';
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
<style type="text/css">
.error{color: red;}
.success{color: green;}
</style>
</head>
<body>
<h2>Contact Us</h2>
<p>Please fill in this form and send us.</p>
<form action="contact.php"method="post">
<p>
<label for="inputName">Name:<sup>*</sup></label>
<input type="text"name="name"id="inputName"value="<?php echo
$name;?>">
<span class="error"><?phpecho$nameErr;?></span>
</p>
<p>
<label for="inputEmail">Email:<sup>*</sup></label>
<input type="text"name="email"id="inputEmail"value="<?php echo
$email;?>">
<span class="error"><?phpecho$emailErr;?></span>
</p>
<p>
<label for="inputSubject">Subject:</label>
<input type="text"name="subject"id="inputSubject"value="<?php
echo $subject;?>">
</p>
<p>
<label for="inputComment">Message:<sup>*</sup></label>
<textarea name="message"id="inputComment"rows="5"cols="30"><?
phpecho$message;?></textarea>
<span class="error"><?phpecho$messageErr;?></span>
</p>
<input type="submit"value="Send">
<input type="reset"value="Reset">
</form>
</body>
</html>
Explanation of code
You might think what that code was all about. OK, let's get straight into it.
Chapter 29
PHP Filters
In this tutorial you will learn how to sanitize and validate user inputs in PHP.
This function takes three parameters out of which the last two are optional. The
first parameter is the value to be filtered, the second parameter is the ID of the
filter to apply, and the third parameter is the array of options related to filter.
Let's see how it works.
Sanitize a String
The following example will sanitize a string by removing all HTML tags from it:
Example
Run this code »
<?php
// Sample user comment
$comment="<h1>Hey there! How are you doing today?</h1>";
Example
Run this code »
<?php
// Sample integer value
$int=20;
Example
Run this code »
<?php
// Sample integer value
$int=0;
Validate IP Addresses
The following example will validate whether the value is a valid IP address or not.
Example
Run this code »
<?php
// Sample IP address
$ip="172.16.254.1";
// Validate sample IP address
if(filter_var($ip,FILTER_VALIDATE_IP)){
echo"The <b>$ip</b> is a valid IP address";
}else{
echo"The <b>$ip</b> is not a valid IP address";
}
?>
You can further apply validation for IPV4 or IPV6 IP addresses by using
the FILTER_FLAG_IPV4 or FILTER_FLAG_IPV6 flags, respectively. Here's an example:
Example
Run this code »
<?php
// Sample IP address
$ip="172.16.254.1";
Example
Run this code »
<?php
// Sample email address
$email="someone@@example.com";
Example
Run this code »
<?php
// Sample website url
$url="http:://www.example.com";
You can also check whether a URL contains query string or not by using the
flag FILTER_FLAG_QUERY_REQUIRED, as shown in the following example:
Example
Run this code »
<?php
// Sample website url
$url="http://www.example.com?topic=filters";
Example
Run this code »
<?php
// Sample integer value
$int=75;
PHP Error Handling
In this tutorial you will 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:
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.
For more error levels, please check out the 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 sofisticated. The
following section describes some of common methods used for handling errors
in PHP:
Example
Download
<?php
// Try to open a non-existent file
$file=fopen("sample.txt","r");
?>
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
Download
<?php
if(file_exists("sample.txt")){
$file=fopen("sample.txt","r");
}else{
die("Error: The file you are trying to access doesn't exist.");
}
?>
Now if you run the above script you will get the error message like this:
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.
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
errfile Specifies the filename of the script file in which the error
occurred, as a string
Example
Download
<?php
// Error handler function
functioncustomError($errno,$errstr){
echo"<b>Error:</b> [$errno] $errstr";
}
?>
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
Download
<?php
// Error handler function
functioncustomError($errno,$errstr){
echo"<b>Error:</b> [$errno] $errstr";
}
// Trigger error
echo($test);
?>
Error Logging
Log Error Messages in a Text File
You can also logs details of the error to the log file, like this:
Example
Download
<?php
functioncalcDivision($dividend,$divisor){
if($divisor==0){
trigger_error("calcDivision(): The divisor cannot be
zero",E_USER_WARNING);
returnfalse;
}else{
return($dividend/$divisor);
}
}
functioncustomError($errno,$errstr,$errfile,$errline,$errcontext)
{
$message=date("Y-m-d H:i:s - ");
$message.="Error: [".$errno."], "."$errstr in $errfile on line
$errline, ";
$message.="Variables:".print_r($errcontext,true)."\r\n";
error_log($message,3,"logs/app_errors.log");
die("There was a problem, please try again.");
}
set_error_handler("customError");
echocalcDivision(10,0);
echo"This will never be printed.";
?>
Example
Download
<?php
functioncalcDivision($dividend,$divisor){
if($divisor==0){
trigger_error("calcDivision(): The divisor cannot be
zero",E_USER_WARNING);
returnfalse;
}else{
return($dividend/$divisor);
}
}
functioncustomError($errno,$errstr,$errfile,$errline,$errcontext)
{
$message=date("Y-m-d H:i:s - ");
$message.="Error: [".$errno."], "."$errstr in $errfile on line
$errline, ";
$message.="Variables:".print_r($errcontext,true)."\r\n";
error_log($message,1,"[email protected]");
die("There was a problem, please try again. Error report
submitted to webmaster.");
}
set_error_handler("customError");
echocalcDivision(10,0);
echo"This will never be printed.";
?>
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.
Consider the following function that calculates division of the two numbers.
Example
Download
<?php
functioncalcDivision($dividend,$divisor){
return($dividend/$divisor);
}
This message doesn't look very informative. Consider the following example that
uses the trigger_error() function to generate the error.
Example
Download
<?php
functioncalcDivision($dividend,$divisor){
if($divisor==0){
trigger_error("The divisor cannot be zero",E_USER_WARNING);
returnfalse;
}else{
return($dividend/$divisor);
}
}
As you can see the error message generated by the second example explains the
problem more clearly as compared to the previous one.
Chapter 31
PHP Classes and Objects
In this tutorial you will learn how to write code in object-oriented style in PHP.
The following sections will describe how classes and objects work in PHP.
Tip: The idea behind Don't Repeat Yourself (DRY) principle is reducing the
repetition of code by abstracting out the code that are common for the
application and placing them at a single place and reuse them instead of
repeating it.
A class acts as a template or blueprint from which lots of individual objects can
be created. When individual objects are created, they inherit the same generic
properties and behaviors, although each object may have different values for
certain properties.
For example, think of a class as a blueprint for a house. The blueprint itself is not
a house, but is a detailed plan of the house. While, an object is like an actual
house built according to that blueprint. We can build several identical houses
from the same blueprint, but each house may have different paints, interiors and
families inside, as shown in the illustration below.
Example
Download
<?php
classRectangle
{
// Declare properties
public$length=0;
public$width=0;
Once a class has been defined, objects can be created from the class with
the new keyword. Class methods and properties can directly be accessed through
this object instance.
Create another PHP file name test.php and put the following code inside it.
Example
Run this code »
<?php
// Include class definition
require"Rectangle.php";
The arrow symbol (->) is an OOP construct that is used to access contained
properties and methods of a given object. Whereas, the pseudo-
variable $this provides a reference to the calling object i.e. the object to which
the method belongs.
The real power of object oriented programming becomes evident when using
multiple instances of the same class, as shown in the following example:
Example
Run this code »
<?php
// Include class definition
require"Rectangle.php";
Example
Run this code »
<?php
classMyClass
{
// Constructor
publicfunction__construct(){
echo'The class "'.__CLASS__.'" was initiated!<br>';
}
// Destructor
publicfunction__destruct(){
echo'The class "'.__CLASS__.'" was destroyed.<br>';
}
}
The PHP code in the above example will produce the following output:
Example
Run this code »
<?php
classMyClass
{
// Constructor
publicfunction__construct(){
echo'The class "'.__CLASS__.'" was initiated!<br>';
}
// Destructor
publicfunction__destruct(){
echo'The class "'.__CLASS__.'" was destroyed.<br>';
}
}
Now, the PHP code in the above example will produce the following output:
Example
Run this code »
<?php
// Include class definition
require"Rectangle.php";
The PHP code in the above example will produce the following output:
The following example will show you how this visibility actually works:
Example
Download
<?php
// Class definition
classAutomobile
{
// Declare properties
public$fuel;
protected$engine;
private$transmission;
}
classCarextendsAutomobile
{
// Constructor
publicfunction__construct(){
echo'The class "'.__CLASS__.'" was initiated!<br>';
}
}
A property declared as static cannot be accessed via the object of that class
though a static method can be, as demonstrated in the following example:
Example
Download
<?php
// Class definition
classHelloClass
{
// Declare a static property
publicstatic$greeting="Hello World!";
Chapter 32
PHP Magic Constants
In this tutorial you will learn how to work with PHP magic constants.
PHP moreover also provide a set of special predefined constants that change
depending on where they are used. These constants are called magic constants.
For example, the value of __LINE__ depends on the line that it's used on in your
script.
Magic constants begin with two underscores and end with two underscores. The
following section describes some of the most useful magical PHP constants.
__LINE__
The __LINE__ constant returns the current line number of the file, like this:
Example
Run this code »
<?php
echo"Line number ".__LINE__."<br>";// Displays: Line number 2
echo"Line number ".__LINE__."<br>";// Displays: Line number 3
echo"Line number ".__LINE__."<br>";// Displays: Line number 4
?><?php
__FILE__
The __FILE__ constant returns full path and name of the PHP file that's being
executed. If used inside an include, the name of the included file is returned.
Example
Download
<?php
// Displays the absolute path of this file
echo"The full path of this file is: ".__FILE__;
?>
__DIR__
The __DIR__ constant returns the directory of the file. If used inside an include, the
directory of the included file is returned. Here's an example:
Example
Download
<?php
// Displays the directory of this file
echo"The directory of this file is: ".__DIR__;
?>
__FUNCTION__
The __FUNCTION__ constant returns the name of the current function.
Example
Run this code »
<?php
functionmyFunction(){
echo"The function name is - ".__FUNCTION__;
}
myFunction();// Displays: The function name is - myFunction
?>
__CLASS__
The __CLASS__ constant returns the name of the current class. Here's an example:
Example
Run this code »
<?php
classMyClass
{
publicfunctiongetClassName(){
return__CLASS__;
}
}
$obj=newMyClass();
echo$obj->getClassName();// Displays: MyClass
?>
__METHOD__
The __METHOD__ constant returns the name of the current class method.
Example
Run this code »
<?php
classSample
{
publicfunctionmyMethod(){
echo__METHOD__;
}
}
$obj=newSample();
$obj->myMethod();// Displays: Sample::myMethod
?>
__NAMESPACE__
The __NAMESPACE__ constant returns the name of the current namespace.
Example
Download
<?php
namespace MyNamespace;
classMyClass
{
publicfunctiongetNamespace(){
return__NAMESPACE__;
}
}
$obj=newMyClass();
echo$obj->getNamespace();// Displays: MyNamespace
?>
Chapter 33
PHP JSON Parsing
In this tutorial you will learn how to encode and decode JSON data in PHP.
What is JSON
JSON stands for JavaScript Object Notation. JSON is a standard lightweight data-
interchange format which is quick and easy to parse and generate.
JSON, like XML, is a text-based format that's easy to write and easy to understand
for both humans and computers, but unlike XML, JSON data structures occupy
less bandwidth than their XML versions. JSON is based on two basic structures:
Example
Run this code »
{
"book":{
"name":"Harry Potter and the Goblet of Fire",
"author":"J. K. Rowling",
"year":2000,
"genre":"Fantasy Fiction",
"bestseller":true
}
}
Example
Run this code »
{
"fruits":[
"Apple",
"Banana",
"Strawberry",
"Mango"
]
}
Example
Run this code »
<?php
// An associative array
$marks=array("Peter"=>65,"Harry"=>80,"John"=>78,"Clark"=>90);
echojson_encode($marks);
?>
Similarly, you can encode the PHP indexed array into a JSON array, like this:
Example
Run this code »
<?php
// An indexed array
$colors=array("Red","Green","Blue","Orange","Yellow");
echojson_encode($colors);
?>
Example
Run this code »
<?php
// An indexed array
$colors=array("Red","Green","Blue","Orange");
echojson_encode($colors,JSON_FORCE_OBJECT);
?>
As you can see in the above examples a non-associative array can be encoded as
array or object. However, an associative array always encoded as object.
Example
Run this code »
<?php
// Store JSON data in a PHP variable
$json='{"Peter":65,"Harry":80,"John":78,"Clark":90}';
var_dump(json_decode($json));
?>
The output of the above example will look something like this:
object(stdClass)#1 (4) { ["Peter"]=> int(65) ["Harry"]=> int(80)
["John"]=> int(78) ["Clark"]=> int(90) }
var_dump(json_decode($json,true));
?>
The output of the above example will look something like this:
array(4) { ["Peter"]=> int(65) ["Harry"]=> int(80) ["John"]=>
int(78) ["Clark"]=> int(90) }
Now let's check out an example that will show you how to decode the JSON data
and access individual elements of the JSON object or array in PHP.
Example
Run this code »
<?php
// Assign JSON encoded string to a PHP variable
$json='{"Peter":65,"Harry":80,"John":78,"Clark":90}';
You can also loop through the decoded data using foreach() loop, like this:
Example
Run this code »
<?php
// Assign JSON encoded string to a PHP variable
$json='{"Peter":65,"Harry":80,"John":78,"Clark":90}';
Example
Run this code »
<?php
// Define recursive function to extract nested values
functionprintValues($arr){
global$count;
global$values;
*/
foreach($arras$key=>$value){
if(is_array($value)){
printValues($value);
}else{
$values[]=$value;
$count++;
returnarray('total'=>$count,'values'=>$values);
$json='{
"book": {
"year": 2000,
"price": {
}
}';
$arr=json_decode($json,true);
$result=printValues($arr);
echoimplode("<br>",$result["values"]);
echo"<hr>";
?>
Chapter 34
PHP Regular Expressions
In this tutorial you will learn how regular expressions work, as well as how to use
them to perform pattern matching in an efficient way in PHP.
PHP (version 5.3 and above) supports Perl style regular expressions via
its preg_ family of functions. Why Perl style regular expressions? Because Perl
(Practical Extraction and Report Language) was the first mainstream programming
language that provided integrated support for regular expressions and it is well
known for its strong support of regular expressions and its extraordinary text
processing and manipulation capabilities.
Let's begin with a brief overview of the commonly used PHP's built-in pattern-
matching functions before delving deep into the world of regular expressions.
Character Classes
Square brackets surrounding a pattern of characters are called a character class
e.g. [abc]. A character class always matches a single character out of a list of
specified characters that means the expression [abc] matches only a, b or c
character.
Negated character classes can also be defined that match any character except
those contained within the brackets. A negated character class is defined by
placing a caret (^) symbol immediately after the opening bracket, like this [^abc].
You can also define a range of characters by using the hyphen ( -) character inside
a character class, like [0-9]. Let's look at some examples of character classes:
The following example will show you how to find whether a pattern exists in a
string or not using the regular expression and PHP preg_match() function:
Example
Run this code »
<?php
$pattern="/ca[kf]e/";
$text="He was eating cake in the cafe.";
if(preg_match($pattern,$text)){
echo"Match found!";
}else{
echo"Match not found.";
}
?>
Similarly, you can use the preg_match_all() function to find all matches within a
string:
Example
Run this code »
<?php
$pattern="/ca[kf]e/";
$text="He was eating cake in the cafe.";
$matches=preg_match_all($pattern,$text,$array);
echo$matches." matches were found.";
?>
Tip: Regular expressions aren't exclusive to PHP. Languages such as Java, Perl,
Python, etc. use the same notation for finding patterns in text.
The following example will show you how to find and replace space with a
hyphen character in a string using regular expression and
PHP preg_replace() function:
Example
Run this code »
<?php
$pattern="/\s/";
$replacement="-";
$text="Earth revolves around\nthe\tSun";
// Replace spaces, newlines and tabs
echopreg_replace($pattern,$replacement,$text);
echo"<br>";
// Replace only spaces
echostr_replace(" ","-",$text);
?>
Repetition Quantifiers
In the previous section we've learnt how to match a single character in a variety
of fashions. But what if you want to match on more than one character? For
example, let's say you want to find out words containing one or more instances
of the letter p, or words containing at least two p's, and so on. This is where
quantifiers come into play. With quantifiers you can specify how many times a
character in a regular expression should match.
The following table lists the various ways to quantify a particular pattern:
The regular expression in the following example will splits the string at comma,
sequence of commas, whitespace, or combination thereof using the
PHP preg_split() function:
Example
Run this code »
<?php
$pattern="/[\s,]+/";
$text="My favourite colors are red, green and blue";
$parts=preg_split($pattern,$text);
// Loop through parts array and display substrings
foreach($partsas$part){
echo$part."<br>";
}
?>
Position Anchors
There are certain situations where you want to match at the beginning or end of
a line, word, or string. To do this you can use anchors. Two common anchors are
caret (^) which represent the start of the string, and the dollar ( $) sign which
represent the end of the string.
The regular expression in the following example will display only those names
from the names array which start with the letter "J" using the
PHP preg_grep() function:
Example
Run this code »
<?php
$pattern="/^J/";
$names=array("Jhon Carter","Clark Kent","John Rambo");
$matches=preg_grep($pattern,$names);
The following example will show you how to perform a global case-insensitive
search using the i modifier and the PHP preg_match_all() function.
Example
Run this code »
<?php
$pattern="/color/i";
$text="Color red is more visible than color blue in daylight.";
$matches=preg_match_all($pattern,$text,$array);
echo$matches." matches were found.";
?>
Similarly, the following example shows how to match at the beginning of every
line in a multi-line string using ^ anchor and m modifier with
PHP preg_match_all() function.
Example
Run this code »
<?php
$pattern="/^color/im";
$text="Color red is more visible than \ncolor blue in daylight.";
$matches=preg_match_all($pattern,$text,$array);
echo$matches." matches were found.";
?>
Word Boundaries
A word boundary character ( \b) helps you search for the words that begins
and/or ends with a pattern. For example, the regexp /\bcar/ matches the words
beginning with the pattern car, and would match cart, carrot, or cartoon, but
would not match oscar.
Similarly, the regexp /car\b/ matches the words ending with the pattern car, and
would match scar, oscar, or supercar, but would not match cart. Likewise,
the /\bcar\b/ matches the words beginning and ending with the pattern car, and
would match only the word car.
The following example will highlight the words beginning with car in bold:
Example
Run this code »
<?php
$pattern='/\bcar\w*/';
$replacement='<b>$0</b>';
$text='Words begining with car: cart, carrot, cartoon. Words
ending with car: scar, oscar, supercar.';
echopreg_replace($pattern,$replacement,$text);
?>
We hope you have understood the basics of regular expression. To learn how to
validate form data using regular expression, please check out the tutorial on PHP
Form Validation.
Chapter 35
PHP Exception Handling
In this tutorial you will learn how to throw and catch exceptions in PHP.
What is an Exception
An exception is a signal that indicates some sort of exceptional event or error has
occurred. Exceptions can be caused due to various reasons, for example,
database connection or query fails, file that you're trying to access doesn't exist,
and so on.
<?php
functiondivision($dividend,$divisor){
// Throw exception if divisor is zero
if($divisor==0){
thrownewException('Division by zero.');
}else{
$quotient=$dividend/$divisor;
echo"<p>$dividend / $divisor = $quotient</p>";
}
}
try{
division(10,2);
division(30,-4);
division(15,0);
// Continue execution
echo"<p>Hello World!</p>";
?>
You might be wondering what this code was all about. Well, let's go through
each part of this code one by one for a better understanding.
Explanation of Code
The PHP's exception handling system has basically four parts: try, throw, catch, and
the Exception class. The following list describes how each part exactly works.
Example
Download
<?php
// Turn off default error reporting
error_reporting(0);
try{
$file="somefile.txt";
You can define a custom exception by extending the Exception class, because
Exception is the base class for all exceptions. The custom exception class inherits
all the properties and methods from PHP's Exception class. You can also add your
custom methods to the custom exception class. Let's check out the following
example:
Example
Download
<?php
// Extending the Exception class
classEmptyEmailExceptionextendsException{}
classInvalidEmailExceptionextendsException{}
$email="[email protected]";
try{
// Throw exception if email is empty
if($email==""){
thrownewEmptyEmailException("<p>Please enter your E-mail address!
</p>");
}
Since these custom exception classes inherits the properties and methods from
the Exception class, so we can use the Exception's class methods
like getMessage(), getLine(), getFile(), etc. to retrieve error information from the
exception object.
Example
Download
<?php
functionhandleUncaughtException($e){
// Display generic error message to the user
echo"Opps! Something went wrong. Please try again, or contact us
if the problem persists.";
// Throw an exception
thrownewException("Testing Exception!");
?>
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 system being used on the
Web today. It is freely available and easy to install, however if you have installed
Wampserver it already there on your machine. MySQL database server offers
several advantages:
MySQL is easy to use, yet extremely powerful, fast, secure, and scalable.
MySQL runs on a wide range of operating systems, including UNIX or
Linux, Microsoft Windows, Apple Mac OS X, and others.
MySQL supports standard SQL (Structured Query Language).
MySQL is ideal database solution for both small and large applications.
MySQL is developed, and distributed by Oracle Corporation.
MySQL includes data security layers that protect sensitive data from
intruders.
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 id, first_name, last_name, email, etc. The
structure of a simple MySQL table that contains person's general information
may look something like this:
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
Tip: Websites like Facebook, Twitter, Wikipedia uses MySQL for their storage
need. So you can easily understand what MySQL is capable of.
Talking to MySQL Databases with SQL
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:
SELECT email FROM persons WHERE first_name="Peter"
If you execute the SQL query above it will return the following record:
Chapter 37
PHP Connect to MySQL Server
In this tutorial you will learn how to connect to the MySQL server using PHP.
While the PDO extension is more portable and supports more than twelve
different databases, MySQLi extension as the name suggests supports MySQL
database only. MySQLi extension however provides an easier way to connect to,
and execute queries on, a MySQL database server. Both PDO and MySQLi offer an
object-oriented API, but MySQLi also offers a procedural API which is relatively
easy for beginners to understand.
Tip: The PHP's MySQLi extension provides both speed and feature benefits over
the PDO extension, so it could be a better choice for MySQL-specific projects.
The following example shows how to connect to MySQL database server using
MySQLi (both procedural and object oriented way) and PDO extension.
Example
Procedural Object Oriented PDO
Download
<?php
$link=mysqli_connect("localhost","root","");
// Check connection
if($link===false){
?>
Example
Procedural Object Oriented PDO
Download
<?php
$link=mysqli_connect("localhost","root","");
// Check connection
if($link===false){
// Close connection
mysqli_close($link);
?>
Chapter 38
PHP MySQL Create Database
In this tutorial you will learn how to create a database in MySQL using PHP.
Let's make a SQL query using the CREATE DATABASE statement, after that we will
execute this SQL query through passing it to the PHP mysqli_query() function to
finally create our database. The following example creates a database
named demo.
Example
Procedural Object Oriented PDO
Download
<?php
$link=mysqli_connect("localhost","root","");
// Check connection
if($link===false){
}
// Attempt create database query execution
if(mysqli_query($link,$sql)){
}else{
// Close connection
mysqli_close($link);
?>
Tip: Setting the PDO::ATTR_ERRMODE attribute to PDO::ERRMODE_EXCEPTION tells PDO to
throw exceptions whenever a database error occurs.
Chapter 39
PHP MySQL Create Tables
In this tutorial you will learn how to create tables in MySQL database using PHP.
Let's make a SQL query using the CREATE TABLE statement, after that we will
execute this SQL query through passing it to the PHP mysqli_query() function to
finally create our table.
Example
Procedural Object Oriented PDO
Download
<?php
$link=mysqli_connect("localhost","root","","demo");
// Check connection
if($link===false){
}
// Attempt create table query execution
)";
if(mysqli_query($link,$sql)){
}else{
// Close connection
mysqli_close($link);
?>
The PHP code in the above example creates a table named persons with four
columns id, first_name, last_name and email inside the demo database.
Notice that each field name is followed by a data type declaration; this
declaration specifies what type of data the column can hold, whether integer,
string, date, etc.
There are a few additional constraints (also called modifiers) that are specified
after the column name in the preceding SQL statement, like NOT NULL, PRIMARY
KEY, AUTO_INCREMENT, etc. Constraints define rules regarding the values allowed in
columns.
Note: Any number of line breaks may occur within a SQL statement, provided
that any line break does not break off keywords, values, expression, etc.
Chapter 40
PHP MySQL INSERT Query
In this tutorial you will learn how to insert records in a MySQL table using PHP.
Inserting Data into a MySQL Database Table
Now that you've understood how to create database and tables in MySQL. In this
tutorial you will learn how to execute SQL query to insert records into a table.
Let's make a SQL query using the INSERT INTO statement with appropriate values,
after that we will execute this insert query through passing it to the
PHP mysqli_query() function to insert data in table. Here's an example, which insert
a new row to the persons table by specifying values for
the first_name, last_name and email fields.
Example
Procedural Object Oriented PDO
Download
<?php
$link=mysqli_connect("localhost","root","","demo");
// Check connection
if($link===false){
if(mysqli_query($link,$sql)){
}else{
// Close connection
mysqli_close($link);
?>
If you remember from the preceding chapter, the 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, by incrementing the previous value by 1.
Inserting Multiple Rows into a Table
You can also insert multiple rows into a table with a single insert query at once.
To do this, include multiple lists of column values within the INSERT
INTO statement, where column values for each row must be enclosed within
parentheses and separated by a comma.
Example
Procedural Object Oriented PDO
Download
<?php
$link=mysqli_connect("localhost","root","","demo");
// Check connection
if($link===false){
}
// Attempt insert query execution
if(mysqli_query($link,$sql)){
}else{
// Close connection
mysqli_close($link);
?>
Now, go to phpMyAdmin (http://localhost/phpmyadmin/) and check out
the persons table data inside demo database. You will find the value for
the id column is assigned automatically by incrementing the value of
previous id by 1.
Note: Any number of line breaks may occur within a SQL statement, provided
that any line break does not break off keywords, values, expression, etc.
Example
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert.php"method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text"name="first_name"id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text"name="last_name"id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text"name="email"id="emailAddress">
</p>
<input type="submit"value="Submit">
</form>
</body>
</html>
Example
Procedural Object Oriented PDO
Download
<?php
$link=mysqli_connect("localhost","root","","demo");
// Check connection
if($link===false){
$first_name=mysqli_real_escape_string($link,
$_REQUEST['first_name']);
$last_name=mysqli_real_escape_string($link,
$_REQUEST['last_name']);
$email=mysqli_real_escape_string($link,$_REQUEST['email']);
if(mysqli_query($link,$sql)){
}else{
}
// Close connection
mysqli_close($link);
?>
In the next chapter we will extend this insert query example and take it one step
further by implementing the prepared statement for better security and
performance.
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 check out the
tutorial on PHP form validation to learn more about sanitizing and validating user
inputs using PHP.
Chapter 41
PHP MySQL Prepared Statements
In this tutorial you will learn how to use prepared statements in MySQL using
PHP.
While, PDO supports both anonymous positional placeholder (?), as well as the
named placeholders. A named placeholder begins with a colon ( :) followed by an
identifier, like this:
INSERT INTO persons (first_name, last_name, email)
VALUES (:first_name, :last_name, :email);
The prepared statement execution consists of two stages: prepare and execute.
The following example will show you how prepared statements actually work:
Example
Procedural Object Oriented PDO
Download
<?php
$link=mysqli_connect("localhost","root","","demo");
// Check connection
if($link===false){
if($stmt=mysqli_prepare($link,$sql)){
mysqli_stmt_bind_param($stmt,"sss",$first_name,$last_name,
$email);
$first_name="Hermione";
$last_name="Granger";
$email="[email protected]";
mysqli_stmt_execute($stmt);
/* Set the parameters values and execute
$first_name="Ron";
$last_name="Weasley";
$email="[email protected]";
mysqli_stmt_execute($stmt);
}else{
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
?>
As you can see in the above example we've prepared the INSERT statement just
once but executed it multiple times by passing the different set of parameters.
The type definition string specify the data types of the corresponding bind
variables and contains one or more of the following four characters:
The number of bind variables and the number of characters in type definition
string must match the number of placeholders in the SQL statement template.
Here's the updated PHP code for inserting the data. If you see the example
carefully you'll find we didn't use the mysqli_real_escape_string() to escape the
user inputs, like we've done in the previous chapter example. Since in prepared
statements, user inputs are never substituted into the query string directly, so
they do not need to be escaped correctly.
Example
Procedural Object Oriented PDO
Download
<?php
$link=mysqli_connect("localhost","root","","demo");
// Check connection
if($link===false){
if($stmt=mysqli_prepare($link,$sql)){
mysqli_stmt_bind_param($stmt,"sss",$first_name,$last_name,
$email);
// Set parameters
$first_name=$_REQUEST['first_name'];
$last_name=$_REQUEST['last_name'];
$email=$_REQUEST['email'];
}else{
}else{
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
?>
Note: Though escaping user inputs is not required in prepared statements, you
should always validate the type and size of the data received from external
sources and enforces appropriate limits to protect against system resources
exploitation.
Chapter 42
For this example we'll use the same persons table that we've created in the PHP
MySQL create tables chapter, which has four
columns id, first_name, last_name and email, where id is the primary key column
and marked with AUTO_INCREMENT flag.
Example
Procedural Object Oriented PDO
Download
<?php
$link=mysqli_connect("localhost","root","","demo");
// Check connection
if($link===false){
if(mysqli_query($link,$sql)){
$last_id=mysqli_insert_id($link);
}else{
// Close connection
mysqli_close($link);
?>
Chapter 43
PHP MySQL SELECT Query
In this tutorial you'll learn how to select records from a MySQL table using PHP.
Selecting Data From 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 tutorial. The
SQL SELECT statement is used to select the records from database tables. Its basic
syntax is as follows:
SELECT column1_name, column2_name, columnN_name FROM table_name;
Let's make a SQL query using the SELECT statement, after that we will execute this
SQL query through passing it to the PHP mysqli_query() function to retrieve the
table data.
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
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
Procedural Object Oriented PDO
Download
<?php
/* Attempt MySQL server connection. Assuming you are running
MySQL
$link=mysqli_connect("localhost","root","","demo");
// Check connection
if($link===false){
if($result=mysqli_query($link,$sql)){
if(mysqli_num_rows($result)>0){
echo"<table>";
echo"<tr>";
echo"<th>id</th>";
echo"<th>first_name</th>";
echo"<th>last_name</th>";
echo"<th>email</th>";
echo"</tr>";
while($row=mysqli_fetch_array($result)){
echo"<tr>";
echo"<td>".$row['id']."</td>";
echo"<td>".$row['first_name']."</td>";
echo"<td>".$row['last_name']."</td>";
echo"<td>".$row['email']."</td>";
echo"</tr>";
echo"</table>";
mysqli_free_result($result);
}else{
echo"No records matching your query were found.";
}else{
// Close connection
mysqli_close($link);
?>
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.
Chapter 44
PHP MySQL WHERE Clause
In this tutorial you will learn how to select the records from a MySQL database
table based on specific conditions using PHP.
Let's make a SQL query using the WHERE clause in SELECT statement, after that we'll
execute this query through passing it to the PHP mysqli_query() function to get
the filtered data.
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
The following PHP code selects all the rows from the persons table where
first_name='john':
Example
Procedural Object Oriented PDO
Download
<?php
$link=mysqli_connect("localhost","root","","demo");
// Check connection
if($link===false){
if($result=mysqli_query($link,$sql)){
if(mysqli_num_rows($result)>0){
echo"<table>";
echo"<tr>";
echo"<th>id</th>";
echo"<th>first_name</th>";
echo"<th>last_name</th>";
echo"<th>email</th>";
echo"</tr>";
while($row=mysqli_fetch_array($result)){
echo"<tr>";
echo"<td>".$row['id']."</td>";
echo"<td>".$row['first_name']."</td>";
echo"<td>".$row['last_name']."</td>";
echo"<td>".$row['email']."</td>";
echo"</tr>";
echo"</table>";
mysqli_free_result($result);
}else{
}else{
// Close connection
mysqli_close($link);
?>
After filtration the result set will look something like this:
+----+------------+-----------+---------------------+
+----+------------+-----------+---------------------+
+----+------------+-----------+---------------------+
Chapter 45
PHP MySQL LIMIT Clause
In this tutorial you will learn how to fetch limited number of records from a
MySQL database table using PHP.
When two parameters are specified, the first parameter specifies the offset
of the first row to return i.e. the starting point, whereas the second parameter
specifies the number of rows to return. The offset of the first row is 0 (not 1).
Whereas, when only one parameter is given, it specifies the maximum
number of rows to return from the beginning of the result set.
For example, to retrieve the first three rows, you can use the following query:
SELECT * FROM persons LIMIT 3;
To retrieve the rows 2-4 (inclusive) of a result set, you can use the following
query:
SELECT * FROM persons LIMIT 1, 3;
+----+------------+-----------+----------------------+
The PHP code in the following example will display just three rows from
the persons table.
Example
Procedural Object Oriented PDO
Download
<?php
$link=mysqli_connect("localhost","root","","demo");
// Check connection
if($link===false){
if($result=mysqli_query($link,$sql)){
if(mysqli_num_rows($result)>0){
echo"<table>";
echo"<tr>";
echo"<th>id</th>";
echo"<th>first_name</th>";
echo"<th>last_name</th>";
echo"<th>email</th>";
echo"</tr>";
while($row=mysqli_fetch_array($result)){
echo"<tr>";
echo"<td>".$row['id']."</td>";
echo"<td>".$row['first_name']."</td>";
echo"<td>".$row['last_name']."</td>";
echo"<td>".$row['email']."</td>";
echo"</tr>";
echo"</table>";
mysqli_free_result($result);
}else{
}else{
// Close connection
mysqli_close($link);
?>
After limiting the result set the output will look something like this:
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
Chapter 46
Let's make a SQL query using the ORDER BY clause in SELECT statement, after that we
will execute this query through passing it to the PHP mysqli_query() function to
get the ordered data. Consider the following persons table inside
the demo database:
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
The PHP code in the following example selects all rows from the persons table
and sorts the result by the first_name column in the alphabetically ascending
order.
Example
Procedural Object Oriented PDO
Download
<?php
$link=mysqli_connect("localhost","root","","demo");
// Check connection
if($link===false){
if($result=mysqli_query($link,$sql)){
if(mysqli_num_rows($result)>0){
echo"<table>";
echo"<tr>";
echo"<th>id</th>";
echo"<th>first_name</th>";
echo"<th>last_name</th>";
echo"<th>email</th>";
echo"</tr>";
while($row=mysqli_fetch_array($result)){
echo"<tr>";
echo"<td>".$row['id']."</td>";
echo"<td>".$row['first_name']."</td>";
echo"<td>".$row['last_name']."</td>";
echo"<td>".$row['email']."</td>";
echo"</tr>";
echo"</table>";
}else{
}else{
// Close connection
mysqli_close($link);
?>
After ordering the result, the result set will look something like this:
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
Tip: By default the ORDER BY clause sort the results in ascending order. If you want
to sort the records in a descending order, you can use the DESC keyword.
Chapter 47
PHP MySQL UPDATE Query
In this tutorial you'll learn how to update the records in a MySQL table using PHP.
Updating Database Table Data
The UPDATE statement is used to change or modify the existing records in a
database table. This statement is typically used in conjugation with
the WHERE clause to apply the changes to only those records that matches specific
criteria.
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
The PHP code in the following example will update the email address of a person
in the persons table whose id is equal to 1.
Example
Procedural Object Oriented PDO
Download
<?php
$link=mysqli_connect("localhost","root","","demo");
// Check connection
if($link===false){
if(mysqli_query($link,$sql)){
}else{
echo"ERROR: Could not able to execute $sql.
".mysqli_error($link);
// Close connection
mysqli_close($link);
?>
After update the persons table will look something like this:
+----+------------+-----------+--------------------------+
+----+------------+-----------+--------------------------+
+----+------------+-----------+--------------------------+
PHP MySQL DELETE Query
In this tutorial you'll learn how to delete records from a MySQL table using PHP.
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
The PHP code in the following example will delete the records of those persons
from the persons table whose first_name is equal to John.
Example
Procedural Object Oriented PDO
Download
<?php
$link=mysqli_connect("localhost","root","","demo");
// Check connection
if($link===false){
if(mysqli_query($link,$sql)){
}else{
}
// Close connection
mysqli_close($link);
?>
After the deletion the persons table will look something like this:
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
As you can see the records has been deleted successfully from the persons table.
Chapter 49
PHP MySQL CRUD Application
In this tutorial you'll learn how to build a CRUD application with PHP and MySQL.
What is CRUD
CRUD is an acronym for Create, Read, Update, and Delete. CRUD operations are
basic data manipulation for database. We've already learned how to perform
create (i.e. insert), read (i.e. select), update and delete operations in previous
chapters. In this tutorial we'll create a simple PHP application to perform all these
operations on a MySQL database table at one place.
Well, let's start by creating the table which we'll use in all of our example.
Example
Download
CREATETABLE employees (
id INTNOTNULLPRIMARYKEYAUTO_INCREMENT,
name VARCHAR(100)NOTNULL,
address VARCHAR(255)NOTNULL,
salary INT(10)NOTNULL
);
We'll later include this config file in other pages using the
PHP require_once() function.
Example
Procedural Object Oriented PDO
Download
<?php
define('DB_SERVER','localhost');
define('DB_USERNAME','root');
define('DB_PASSWORD','');
define('DB_NAME','demo');
$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);
// Check connection
if($link===false){
?>
If you've downloaded the Object Oriented or PDO code examples using the
download button, please remove the text "-oo-format" or "-pdo-format" from file
names before testing the code.
We'll also add a create button on the top of the data grid that can be used for
creating new records in the employees table. Create a file named "index.php" and
put the following code in it:
Example
Procedural Object Oriented PDO
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.m
in.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap
.js"></script>
<style type="text/css">
.wrapper{
width: 650px;
margin: 0 auto;
.page-header h2{
margin-top: 0;
table tr td:last-child a{
margin-right: 15px;
</style>
<script type="text/javascript">
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
</div>
<?php
if($result=mysqli_query($link,$sql)){
if(mysqli_num_rows($result)>0){
echo"<thead>";
echo"<tr>";
echo"<th>#</th>";
echo"<th>Name</th>";
echo"<th>Address</th>";
echo"<th>Salary</th>";
echo"<th>Action</th>";
echo"</tr>";
echo"</thead>";
echo"<tbody>";
while($row=mysqli_fetch_array($result)){
echo"<tr>";
echo"<td>".$row['id']."</td>";
echo"<td>".$row['name']."</td>";
echo"<td>".$row['address']."</td>";
echo"<td>".$row['salary']."</td>";
echo"<td>";
echo"</td>";
echo"</tr>";
}
echo"</tbody>";
echo"</table>";
mysqli_free_result($result);
}else{
}else{
// Close connection
mysqli_close($link);
?>
</div>
</div>
</div>
</div>
</body>
</html>
Once employees table is populated with some records the landing page i.e. the
CRUD data grid may look something like the picture shown below:
Tip: We've used the Bootstrap framework to make this CRUD application layout
quickly and beautifully. Bootstrap is the most popular and powerful front-end
framework for faster and easier responsive web development. Please, checkout
the Bootstrap tutorial section to learn more about this framework.
Let's create a file named "create.php" and put the following code inside it. It will
generate a web form that can be used to insert records in the employees table.
Example
Procedural Object Oriented PDO
Download
<?php
require_once"config.php";
$name=$address=$salary="";
$name_err=$address_err=$salary_err="";
if($_SERVER["REQUEST_METHOD"]=="POST"){
// Validate name
$input_name=trim($_POST["name"]);
if(empty($input_name)){
}else{
$name=$input_name;
// Validate address
$input_address=trim($_POST["address"]);
if(empty($input_address)){
}else{
$address=$input_address;
// Validate salary
$input_salary=trim($_POST["salary"]);
if(empty($input_salary)){
}elseif(!ctype_digit($input_salary)){
}else{
$salary=$input_salary;
if(empty($name_err)&&empty($address_err)&&empty($salary_err)){
if($stmt=mysqli_prepare($link,$sql)){
// Set parameters
$param_name=$name;
$param_address=$address;
$param_salary=$salary;
if(mysqli_stmt_execute($stmt)){
header("location: index.php");
exit();
}else{
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Create Record</h2>
</div>
<p>Please fill this form and submit to add employee record to the
database.</p>
<label>Name</label>
<input type="text"name="name"class="form-control"value="<?php
echo $name;?>">
<span class="help-block"><?phpecho$name_err;?></span>
</div>
<label>Address</label>
<textarea name="address"class="form-control"><?phpecho$address;?
></textarea>
<span class="help-block"><?phpecho$address_err;?></span>
</div>
<input type="text"name="salary"class="form-control"value="<?php
echo $salary;?>">
<span class="help-block"><?phpecho$salary_err;?></span>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
The same "create.php" file will display the HTML form and process the submitted
form data. It will also perform basic validation on user inputs (line no-11 to 37)
before saving the data.
Creating the Read Page
Now it's time to build the Read functionality of our CRUD application.
Let's create a file named "read.php" and put the following code inside it. It will
simply retrieve the records from the employees table based the id attribute of the
employee.
Example
Procedural Object Oriented PDO
Download
<?php
if(isset($_GET["id"])&&!empty(trim($_GET["id"]))){
require_once"config.php";
if($stmt=mysqli_prepare($link,$sql)){
// Set parameters
$param_id=trim($_GET["id"]);
if(mysqli_stmt_execute($stmt)){
$result=mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result)==1){
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$name=$row["name"];
$address=$row["address"];
$salary=$row["salary"];
}else{
header("location: error.php");
exit();
}else{
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
}else{
header("location: error.php");
exit();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>View Record</title>
<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h1>View Record</h1>
</div>
<div class="form-group">
<label>Name</label>
<p class="form-control-static"><?phpecho$row["name"];?></p>
</div>
<div class="form-group">
<label>Address</label>
<p class="form-control-static"><?phpecho$row["address"];?></p>
</div>
<div class="form-group">
<label>Salary</label>
<p class="form-control-static"><?phpecho$row["salary"];?></p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Creating the Update Page
Similarly, we can build the Update functionality of our CRUD application.
Let's create a file named "update.php" and put the following code inside it. It will
update the existing records in the employees table based the id attribute of the
employee.
Example
Procedural Object Oriented PDO
Download
<?php
require_once"config.php";
$name=$address=$salary="";
$name_err=$address_err=$salary_err="";
$id=$_POST["id"];
// Validate name
$input_name=trim($_POST["name"]);
if(empty($input_name)){
}elseif(!
filter_var($input_name,FILTER_VALIDATE_REGEXP,array("options"=>ar
ray("regexp"=>"/^[a-zA-Z\s]+$/")))){
}else{
$name=$input_name;
if(empty($input_address)){
}else{
$address=$input_address;
// Validate salary
$input_salary=trim($_POST["salary"]);
if(empty($input_salary)){
}elseif(!ctype_digit($input_salary)){
}else{
$salary=$input_salary;
}
// Check input errors before inserting in database
if(empty($name_err)&&empty($address_err)&&empty($salary_err)){
if($stmt=mysqli_prepare($link,$sql)){
mysqli_stmt_bind_param($stmt,"sssi",$param_name,$param_address,
$param_salary,$param_id);
// Set parameters
$param_name=$name;
$param_address=$address;
$param_salary=$salary;
$param_id=$id;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
header("location: index.php");
exit();
}else{
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
}else{
if(isset($_GET["id"])&&!empty(trim($_GET["id"]))){
$id=trim($_GET["id"]);
if($stmt=mysqli_prepare($link,$sql)){
mysqli_stmt_bind_param($stmt,"i",$param_id);
// Set parameters
$param_id=$id;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result=mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result)==1){
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$name=$row["name"];
$address=$row["address"];
$salary=$row["salary"];
}else{
header("location: error.php");
exit();
}
}else{
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
}else{
header("location: error.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update Record</title>
<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Update Record</h2>
</div>
<label>Name</label>
<input type="text"name="name"class="form-control"value="<?php
echo $name;?>">
<span class="help-block"><?phpecho$name_err;?></span>
</div>
<label>Address</label>
<textarea name="address"class="form-control"><?phpecho$address;?
></textarea>
<span class="help-block"><?phpecho$address_err;?></span>
</div>
<label>Salary</label>
<input type="text"name="salary"class="form-control"value="<?php
echo $salary;?>">
<span class="help-block"><?phpecho$salary_err;?></span>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Let's create a file named "delete.php" and put the following code inside it. It will
delete the existing records from the employees table based the id attribute of the
employee.
Example
Procedural Object Oriented PDO
Download
<?php
if(isset($_POST["id"])&&!empty($_POST["id"])){
require_once"config.php";
if($stmt=mysqli_prepare($link,$sql)){
mysqli_stmt_bind_param($stmt,"i",$param_id);
// Set parameters
$param_id=trim($_POST["id"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
header("location: index.php");
exit();
}else{
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
}else{
// Check existence of id parameter
if(empty(trim($_GET["id"]))){
header("location: error.php");
exit();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>View Record</title>
<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h1>Delete Record</h1>
</div>
<p>
</p>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Creating the Error Page
At the end, let's create one more file "error.php". This page will be displayed if
request is invalid i.e. if id parameter is missing from the URL query string or it is
not valid.
Example
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error</title>
<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 750px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h1>Invalid Request</h1>
</div>
<div class="alert alert-danger fade in">
<p>Sorry, you've made an invalid request. Please <a
href="index.php"class="alert-link">go back</a> and try again.</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
After a long journey finally we've finished our CRUD application with PHP and
MySQL. We recommend you to check out PHP & MySQL database tutorial
section from the beginning, if you haven't already covered, for a better
understanding of each and every part of this tutorial.
Chapter 48
In this tutorial we're going to create a live search box that will search
the countries table and show the results asynchronously. But, first of all we need
to create this table.
Example
Download
CREATETABLE countries (
id INTNOTNULLPRIMARYKEYAUTO_INCREMENT,
name VARCHAR(50)NOTNULL
);
After creating the table, you need to populate it with some data using
the SQL INSERT statement. Alternatively, you can download the
prepopulated countries table by clicking the download button and import it in
your MySQL database.
Create a PHP file named "search-form.php" and put the following code inside of
it.
Example
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Live MySQL Database Search</title>
<style type="text/css">
body{
font-family: Arail, sans-serif;
}
/* Formatting search box */
.search-box{
width: 300px;
position: relative;
display: inline-block;
font-size: 14px;
}
.search-box input[type="text"]{
height: 32px;
padding: 5px 10px;
border: 1px solid #CCCCCC;
font-size: 14px;
}
.result{
position: absolute;
z-index: 999;
top: 100%;
left: 0;
}
.search-box input[type="text"], .result{
width: 100%;
box-sizing: border-box;
}
/* Formatting result items */
.result p{
margin: 0;
padding: 7px 10px;
border: 1px solid #CCCCCC;
border-top: none;
cursor: pointer;
}
.result p:hover{
background: #f2f2f2;
}
</style>
<script src="https://code.jquery.com/jquery-
1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input",function(){
/* Get input value on change */
var inputVal =$(this).val();
var resultDropdown =$(this).siblings(".result");
if(inputVal.length){
$.get("backend-search.php",{term:
inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
}else{
resultDropdown.empty();
}
});
Download
<?php
$link=mysqli_connect("localhost","root","","demo");
// Check connection
if($link===false){
if(isset($_REQUEST["term"])){
mysqli_stmt_bind_param($stmt,"s",$param_term);
// Set parameters
$param_term=$_REQUEST["term"].'%';
if(mysqli_stmt_execute($stmt)){
$result=mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo"<p>".$row["name"]."</p>";
}else{
}else{
// Close statement
mysqli_stmt_close($stmt);
// close connection
mysqli_close($link);
?>
The SQL SELECT statement is used in combination with the LIKE operator (line no-
16) to find the matching records in countries database table. We've implemented
the prepared statement for better search performance as well as to prevent
the SQL injection attack.
Note: Always filter and validate user input before using it in a SQL statement. You
can also use PHP mysqli_real_escape_string() function to escape special characters
in a user input and create a legal SQL string to protect against SQL injection.
Chapter 49
Example
Download
CREATETABLE users (
id INTNOTNULLPRIMARYKEYAUTO_INCREMENT,
username VARCHAR(50)NOTNULLUNIQUE,
password VARCHAR(255)NOTNULL,
created_at DATETIMEDEFAULTCURRENT_TIMESTAMP
);
Please check out the tutorial on SQL CREATE TABLE statement for the detailed
information about syntax for creating tables in MySQL database system.
Example
Procedural Object Oriented PDO
Download
<?php
define('DB_SERVER','localhost');
define('DB_USERNAME','root');
define('DB_PASSWORD','');
define('DB_NAME','demo');
$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);
// Check connection
if($link===false){
?>
If you've downloaded the Object Oriented or PDO code examples using the
download button, please remove the text "-oo-format" or "-pdo-format" from file
names before testing the code.
This script will also generate errors if a user tries to submit the form without
entering any value, or if username entered by the user is already taken by
another user.
Example
Procedural Object Oriented PDO
Download
<?php
require_once"config.php";
$username=$password=$confirm_password="";
$username_err=$password_err=$confirm_password_err="";
if($_SERVER["REQUEST_METHOD"]=="POST"){
// Validate username
if(empty(trim($_POST["username"]))){
}else{
if($stmt=mysqli_prepare($link,$sql)){
mysqli_stmt_bind_param($stmt,"s",$param_username);
// Set parameters
$param_username=trim($_POST["username"]);
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt)==1){
}else{
$username=trim($_POST["username"]);
}else{
}
// Close statement
mysqli_stmt_close($stmt);
// Validate password
if(empty(trim($_POST["password"]))){
}elseif(strlen(trim($_POST["password"]))<6){
}else{
$password=trim($_POST["password"]);
}else{
$confirm_password=trim($_POST["confirm_password"]);
if(empty($password_err)&&($password!=$confirm_password)){
if(empty($username_err)&&empty($password_err)&&empty($confirm_pas
sword_err)){
if($stmt=mysqli_prepare($link,$sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt,"ss",$param_username,
$param_password);
// Set parameters
$param_username=$username;
$param_password=password_hash($password,PASSWORD_DEFAULT);//
Creates a password hash
if(mysqli_stmt_execute($stmt)){
header("location: login.php");
}else{
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">
<style type="text/css">
</style>
</head>
<body>
<div class="wrapper">
<h2>Sign Up</h2>
<label>Username</label>
<input type="text"name="username"class="form-control"value="<?php
echo $username;?>">
<span class="help-block"><?phpecho$username_err;?></span>
</div>
<label>Password</label>
<input type="password"name="password"class="form-
control"value="<?php echo $password;?>">
<span class="help-block"><?phpecho$password_err;?></span>
</div>
<label>Confirm Password</label>
<input type="password"name="confirm_password"class="form-
control"value="<?php echo $confirm_password;?>">
<span class="help-block"><?phpecho$confirm_password_err;?></span>
</div>
<div class="form-group">
</form>
</div>
</body>
</html>
— The output of the above example (i.e. signup form) will look something like
this:
At the time of login we'll verify the given password with the password hash
stored in the database using the PHP password_verify() function, as demonstrated
in the next example.
Example
Procedural Object Oriented PDO
Download
<?php
// Initialize the session
session_start();
if(isset($_SESSION["loggedin"])&&$_SESSION["loggedin"]===true){
header("location: welcome.php");
exit;
require_once"config.php";
$username=$password="";
$username_err=$password_err="";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"]=="POST"){
if(empty(trim($_POST["username"]))){
}else{
$username=trim($_POST["username"]);
if(empty(trim($_POST["password"]))){
}else{
$password=trim($_POST["password"]);
}
// Validate credentials
if(empty($username_err)&&empty($password_err)){
if($stmt=mysqli_prepare($link,$sql)){
mysqli_stmt_bind_param($stmt,"s",$param_username);
// Set parameters
$param_username=$username;
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt)==1){
mysqli_stmt_bind_result($stmt,$id,$username,$hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password,$hashed_password)){
session_start();
$_SESSION["loggedin"]=true;
$_SESSION["id"]=$id;
$_SESSION["username"]=$username;
// Redirect user to welcome page
header("location: welcome.php");
}else{
}else{
}else{
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">
<style type="text/css">
</style>
</head>
<body>
<div class="wrapper">
<h2>Login</h2>
<label>Username</label>
<input type="text"name="username"class="form-control"value="<?php
echo $username;?>">
<span class="help-block"><?phpecho$username_err;?></span>
</div>
<div class="form-group <?php echo (!empty($password_err))?'has-
error':'';?>">
<label>Password</label>
<input type="password"name="password"class="form-control">
<span class="help-block"><?phpecho$password_err;?></span>
</div>
<div class="form-group">
</div>
</form>
</div>
</body>
</html>
— The output of the above example (i.e. login form) will look something like this:
Step 2: Creating the Welcome Page
Here's the code of our "welcome.php" file, where user is redirected after
successful login.
Example
Download
<?php
// Initialize the session
session_start();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">
<style type="text/css">
body{font: 14px sans-serif;text-align: center;}
</style>
</head>
<body>
<div class="page-header">
<h1>Hi, <b><?phpechohtmlspecialchars($_SESSION["username"]);?
></b>. Welcome to our site.</h1>
</div>
<p>
<a href="reset-password.php"class="btn btn-warning">Reset Your
Password</a>
<a href="logout.php"class="btn btn-danger">Sign Out of Your
Account</a>
</p>
</body>
</html>
If data comes from external sources like form filled in by anonymous users, there
is a risk that it may contain malicious script indented to launch cross-site scripting
(XSS) attacks. Therefore, you must escape this data using the
PHP htmlspecialchars() function before displaying it in the browser, so that any
HTML tag it contains becomes harmless.
Example
Download
<?php
// Initialize the session
session_start();
Let's create a file named "reset-password.php" and place the following code
inside it.
Example
Procedural Object Oriented PDO
Download
<?php
session_start();
if(!isset($_SESSION["loggedin"])||$_SESSION["loggedin"]!==true){
header("location: login.php");
exit;
require_once"config.php";
$new_password=$confirm_password="";
$new_password_err=$confirm_password_err="";
if($_SERVER["REQUEST_METHOD"]=="POST"){
if(empty(trim($_POST["new_password"]))){
$new_password_err="Please enter the new password.";
}elseif(strlen(trim($_POST["new_password"]))<6){
}else{
$new_password=trim($_POST["new_password"]);
if(empty(trim($_POST["confirm_password"]))){
}else{
$confirm_password=trim($_POST["confirm_password"]);
if(empty($new_password_err)&&($new_password!=$confirm_password)){
}
// Check input errors before updating the database
if(empty($new_password_err)&&empty($confirm_password_err)){
if($stmt=mysqli_prepare($link,$sql)){
mysqli_stmt_bind_param($stmt,"si",$param_password,$param_id);
// Set parameters
$param_password=password_hash($new_password,PASSWORD_DEFAULT);
$param_id=$_SESSION["id"];
if(mysqli_stmt_execute($stmt)){
// Password updated successfully. Destroy the session, and
redirect to login page
session_destroy();
header("location: login.php");
exit();
}else{
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reset Password</title>
<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">
<style type="text/css">
</style>
</head>
<body>
<div class="wrapper">
<h2>Reset Password</h2>
<label>New Password</label>
<input type="password"name="new_password"class="form-
control"value="<?php echo $new_password;?>">
<span class="help-block"><?phpecho$new_password_err;?></span>
</div>
<label>Confirm Password</label>
<input type="password"name="confirm_password"class="form-
control">
<span class="help-block"><?phpecho$confirm_password_err;?></span>
</div>
<div class="form-group">
<input type="submit"class="btn btn-primary"value="Submit">
</div>
</form>
</div>
</body>
</html>