0% found this document useful (0 votes)
12 views64 pages

WEB Designing Notes

The document provides an overview of PHP as a server-side scripting language used for web development, highlighting its features such as open-source nature, ease of learning, and database integration. It also covers the installation of local server environments like XAMPP and WAMP, the benefits of using PHP with MySQL, and fundamental concepts of object-oriented programming in PHP. Additionally, it details the server-client environment, web browser interactions, and basic syntax and data types in PHP.

Uploaded by

vaibmatic
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views64 pages

WEB Designing Notes

The document provides an overview of PHP as a server-side scripting language used for web development, highlighting its features such as open-source nature, ease of learning, and database integration. It also covers the installation of local server environments like XAMPP and WAMP, the benefits of using PHP with MySQL, and fundamental concepts of object-oriented programming in PHP. Additionally, it details the server-client environment, web browser interactions, and basic syntax and data types in PHP.

Uploaded by

vaibmatic
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Subject: Web Development using PHP & MySQL

UNIT 1
Introduction to php:
PHP (Hypertext Preprocessor) is a popular open-source scripting language that is widely used for web
development. It was originally designed for creating dynamic web pages, and has since evolved to
become a powerful server-side scripting language that can be used to build a wide range of web
applications.
PHP was created in 1994 by Rasmus Lerdorf, and it has since been developed and maintained by a large
community of developers around the world. It is a server-side scripting language, which means that PHP
code is executed on the server before the web page is sent to the client's browser. This allows PHP to be
used for a wide range of tasks, including generating dynamic content, processing form data, interacting
with databases, and more.
Some of the key features of PHP include:
Open-source: PHP is a free and open-source programming language, which means that anyone can use,
modify, and distribute it without any licensing fees.
Easy to learn: PHP has a simple and straightforward syntax that is easy to learn, even for beginners. It is
also supported by a large community of developers who provide tutorials, documentation, and other
resources to help new users get started.
Cross-platform: PHP is compatible with a wide range of operating systems and web servers, including
Windows, Linux, Apache, and Nginx.
Integration with databases: PHP has built-in support for many popular databases, including MySQL,
PostgreSQL, and Oracle, making it easy to create dynamic web applications that interact with databases.
Object-oriented programming: PHP supports object-oriented programming (OOP), which allows
developers to write more organized and maintainable code.
Overall, PHP is a versatile and widely used programming language that is well-suited for web
development. Its open-source nature, ease of use, and broad community support have made it a popular
choice for building a wide range of web applications.
Installation of XAMPP and WAMP server for php:
XAMPP and WAMP are two popular software packages that allow developers to create a local web
server environment for testing and developing PHP applications. Here are the steps to install XAMPP
and WAMP server for PHP:
Installing XAMPP:
1. Download the XAMPP package from the Apache Friends website
([Link]
2. Run the XAMPP installer file and follow the installation wizard.
3. Choose the components you want to install. By default, XAMPP installs Apache, MySQL, PHP,
and Perl.
4. Choose the installation directory where you want to install XAMPP.
5. Complete the installation wizard.
6. Once installed, start the XAMPP Control Panel and start the Apache and MySQL services.
7. Open your web browser and type "[Link] in the address bar. This should open the
XAMPP homepage, indicating that XAMPP is installed and running correctly.
Installing WAMP:
1. Download the WAMP server package from the WampServer website
([Link]
2. Run the WAMP server installer file and follow the installation wizard.
3. Choose the installation directory where you want to install WAMP.

1
Subject: Web Development using PHP & MySQL

4. Choose the components you want to install. By default, WAMP installs Apache, MySQL, and
PHP.
5. Complete the installation wizard.
6. Once installed, start the WAMP server by clicking on the WAMP icon in the system tray and
selecting "Start All Services".
7. Open your web browser and type "[Link] in the address bar. This should open the
WAMP homepage, indicating that WAMP is installed and running correctly.
8. Once you have XAMPP or WAMP installed and running, you can start creating PHP
applications and testing them locally before deploying them to a live server.
Benefits of using PHP MYSQL:
There are many benefits of using PHP and MySQL together for web development:
 Open-source: Both PHP and MySQL are open-source technologies, which means that they are
free to use and can be easily customized to meet the needs of any project.
 Cross-platform compatibility: PHP and MySQL can be used on a wide range of operating
systems, including Windows, Linux, and Mac OS, making it easy to develop applications that
can be used on any platform.
 Easy to learn: PHP and MySQL both have a simple and straightforward syntax, making them
easy to learn and use, even for beginners.
 Fast and efficient: PHP is a server-side scripting language, which means that it runs on the server
and generates HTML pages that are sent to the client's browser. This makes PHP applications
fast and efficient, as the processing is done on the server.
 Database integration: MySQL is a popular open-source relational database management system,
and it integrates seamlessly with PHP, making it easy to build dynamic web applications that
interact with databases.
 Scalability: PHP and MySQL are highly scalable, meaning that they can handle large amounts of
data and traffic without slowing down or crashing.
 Community support: PHP and MySQL both have large and active developer communities,
providing users with access to a wide range of resources, including tutorials, documentation, and
support forums.
Overall, using PHP and MySQL together provides developers with a powerful and flexible platform for
building dynamic, scalable, and efficient web applications.
Server client environment in PHP:
In a server-client environment for PHP, the server is responsible for running the PHP scripts and
generating HTML pages that are sent to the client's browser. The client's browser then interprets the
HTML and displays the web page to the user.
Here's how the server-client environment for PHP works:
1. The client requests a web page from the server by typing in a URL or clicking on a link.
2. The server receives the request and checks if it corresponds to a PHP script.
3. If the requested page is a PHP script, the server runs the script and generates an HTML page that
is sent back to the client.
4. The client's browser receives the HTML page and interprets it, displaying the web page to the
user.
5. If the web page contains any dynamic content, such as data from a database or user input, the
client sends a request back to the server, and the server generates a new HTML page with the
updated content.
In this server-client environment, the server is responsible for handling the processing and generation of
the HTML pages, while the client's browser is responsible for rendering the pages and handling user
2
Subject: Web Development using PHP & MySQL

interactions. PHP provides a powerful server-side scripting language that allows developers to create
dynamic and interactive web applications that can be deployed on a wide range of server environments.
Web Browser in PHP:
A web browser is a software application that is used to access and view web pages on the internet. It
retrieves information from web servers and displays it on the user's computer or device.
The primary function of a web browser is to provide a user interface for browsing the internet,
displaying web pages, and navigating between them. Web browsers use Hypertext Transfer Protocol
(HTTP) to communicate with web servers and retrieve web pages, and they use Hypertext Markup
Language (HTML) to interpret and display the content of those pages.
Web browsers typically include a variety of features, such as bookmarks or favorites to save frequently
visited web pages, tabbed browsing to allow users to have multiple web pages open at once, and various
options for customizing the browser's appearance and behavior.
Some popular web browsers include Google Chrome, Mozilla Firefox, Microsoft Edge, Safari, and
Opera. Each browser has its own set of features, user interface, and compatibility with web standards
and technologies.
In addition to displaying web pages, modern web browsers can also run web applications, such as email
clients, word processors, and photo editors. Web browsers can also support browser extensions and add-
ons, which can add additional features and functionality to the browser.

PHP is a server-side scripting language, which means that it runs on the server and generates HTML
pages that are sent to the client's browser. The client's browser then interprets the HTML and displays
the web page to the user.
Here are some ways in which PHP interacts with the client's browser:
1. Generating HTML: PHP is used to generate HTML pages dynamically, based on user input or
other factors. The PHP code is processed on the server, and the resulting HTML is sent to the
client's browser for rendering.
2. Handling form submissions: When a user submits a form on a web page, the data is sent to the
server for processing. PHP can be used to handle the form submission, validate the input, and
update the database or generate a response page.
3. Handling cookies and sessions: PHP can be used to manage cookies and sessions, which are used
to store information about the user's preferences and activity on the website.
4. Handling redirects: PHP can be used to handle redirects, which are used to redirect the user to a
different page or URL based on certain conditions.
5. Handling client-side scripting: While PHP is primarily a server-side scripting language, it can
also be used to generate client-side scripts, such as JavaScript, which are executed on the client's
browser.
Overall, PHP plays a crucial role in web development by providing a powerful server-side scripting
language that allows developers to create dynamic, interactive, and responsive web applications that can
be deployed on a wide range of server environments and interact with the client's browser in various
ways.
Web Server Installation & Configuration Files in PHP:
To install and configure a web server for PHP development, you will need to follow a few steps:
1. Choose a web server: There are many web servers available, including Apache, Nginx, and
Microsoft IIS. Apache is one of the most popular web servers and is widely used for PHP
development.

3
Subject: Web Development using PHP & MySQL

2. Install the web server: Once you have chosen a web server, you will need to download and install
it on your computer. Follow the instructions provided by the web server software to complete the
installation.
3. Install PHP: After installing the web server, you will need to install PHP. Download the PHP
software from the official website and follow the installation instructions.
4. Configure PHP with the web server: After installing PHP, you will need to configure it to work
with the web server. This usually involves modifying the web server's configuration file to
include the path to the PHP executable.
5. Test the installation: Once you have completed the installation and configuration, you should test
the setup to ensure that everything is working properly. Create a simple PHP script and place it
in the web server's document root directory. Then, navigate to the script in your web browser and
ensure that it is executed properly.
The configuration files that are used to set up and configure the web server and PHP depend on the
specific software that you are using. For example, if you are using Apache as your web server, the
configuration files are typically located in the /etc/apache2/ directory on Linux or macOS, or in the
C:\Program Files (x86)\Apache Group\Apache2\conf directory on Windows. The specific configuration
files that you will need to modify will vary depending on your setup, but common files include
[Link] for Apache and [Link] for PHP.
OOPs with PHP:
Object-oriented programming (OOP) is a programming paradigm that is used to model complex systems
by representing them as a collection of objects that interact with each other. PHP supports OOP, which
allows developers to write modular, reusable, and scalable code.
Here are some key concepts of OOP in PHP:
1. Classes and Objects: A class is a blueprint for creating objects, and an object is an instance of a
class. In PHP, classes are defined using the class keyword, and objects are created using the new
keyword.
2. Properties: Properties are variables that belong to an object. They can be defined within a class
using the public, private, or protected keywords to control their visibility.
3. Methods: Methods are functions that belong to an object. They can be defined within a class
using the public, private, or protected keywords to control their visibility.
4. Inheritance: Inheritance is a mechanism that allows a class to inherit properties and methods
from another class. In PHP, inheritance is achieved using the extends keyword.
5. Polymorphism: Polymorphism is a concept that allows objects of different classes to be treated
as if they were of the same class. This is achieved in PHP through interfaces and abstract classes.
6. Encapsulation: Encapsulation is the concept of hiding implementation details and exposing only
the necessary information to the outside world. In PHP, this is achieved through access modifiers
such as public, private, and protected.
Using OOP in PHP allows developers to create code that is more modular, maintainable, and scalable. It
also allows for better code reuse, as objects can be easily instantiated and used throughout an
application.
Language basics of PHP:
Here are some of the basic concepts of PHP:
1. Variables: PHP variables are used to store data values, such as numbers or strings. Variables are
declared using the $ symbol, followed by the variable name.
2. Data Types: PHP supports several data types, including integers, floating-point numbers, strings,
and booleans.

4
Subject: Web Development using PHP & MySQL

3. Operators: PHP supports a range of operators, including arithmetic operators (+, -, *, /),
assignment operators (=, +=, -=), comparison operators (==, !=, >, <), and logical operators (&&,
||, !).
4. Conditional Statements: PHP includes conditional statements such as if, else, and switch that
allow for different blocks of code to be executed based on the result of a condition.
5. Loops: PHP includes loop statements such as for, while, and foreach that allow for code to be
executed repeatedly.
6. Functions: PHP functions are used to encapsulate blocks of code that can be reused throughout a
program. Functions are declared using the function keyword.
7. Arrays: PHP arrays are used to store collections of data. Arrays can be indexed using numerical
keys or associative keys.
8. Superglobals: PHP includes several predefined variables, called superglobals, that can be
accessed from anywhere in a program. Some common superglobals include $_GET, $_POST,
$_SERVER, and $_SESSION.
These are just a few of the basic concepts of PHP. PHP also includes a range of built-in functions, as
well as support for object-oriented programming and database integration.
Syntax in php:
The syntax of PHP is similar to other programming languages, but there are a few unique aspects to be
aware of. Here are some key syntax elements of PHP:
1. Statements: PHP statements are typically terminated with a semicolon (;). Statements can be
grouped together using curly braces ({}) to create code blocks.
2. Comments: PHP comments are used to add explanatory text to code without affecting its
functionality. Single-line comments are created using // or #, while multi-line comments are
created using /* and */.
3. Variables: PHP variables are declared using the $ symbol, followed by the variable name.
Variable names can contain letters, numbers, and underscores, but cannot start with a number.
4. Strings: PHP strings are enclosed in quotes (single or double), and can include variables and
special characters using escape sequences (such as \n for a new line).
5. Operators: PHP supports a range of operators, including arithmetic operators (+, -, *, /),
assignment operators (=, +=, -=), comparison operators (==, !=, >, <), and logical operators (&&,
||, !).
6. Functions: PHP functions are declared using the function keyword, followed by the function
name and any parameters. The function block is enclosed in curly braces ({}) and can include
return statements to return values.
7. Control Structures: PHP includes control structures such as if, else, for, while, switch, and
foreach, which allow for different blocks of code to be executed based on conditions or
iterations.
8. Arrays: PHP arrays are created using square brackets ([]), and can include both numerical and
associative keys.
These are just a few of the key syntax elements of PHP. PHP also includes support for object-oriented
programming, database integration, and a range of other advanced features.
Example:
<?php

// This is a single-line comment

/*
5
Subject: Web Development using PHP & MySQL

This is a multi-line
comment
*/
$name = "John"; // This declares a variable called $name and assigns it the value "John"
?>
Variable,constants and data type:
Variables, constants, and data types are key concepts in PHP programming. Here is an explanation of
each with an example:
Variables: A variable is a container that holds a value that can be used and changed throughout the
script. In PHP, variables are declared using the $ symbol, followed by the variable name. Here's an
example:
$name = "John";
In this example, we declare a variable called $name and assign it the value "John".
Constants: A constant is a value that cannot be changed throughout the script. In PHP, constants are
declared using the define() function. Here's an example:
define("PI", 3.14);
In this example, we declare a constant called PI and assign it the value 3.14.
Data types: PHP supports several data types, including strings, integers, floats, booleans, arrays, and
objects. Here are examples of each:
// String data type
$name = "John";

// Integer data type


$age = 25;

// Float data type


$price = 19.99;

// Boolean data type


$is_valid = true;

// Array data type


$colors = array("red", "green", "blue");

// Object data type


class Person {
public $name;
public $age;
}

$person = new Person();


$person->name = "John";
$person->age = 25;
In this example, we declare a string variable called $name with the value "John", an integer variable
called $age with the value 25, a float variable called $price with the value 19.99, a boolean variable
called $is_valid with the value true, an array variable called $colors with three string values, and an
object variable called $person with a name and age property.
6
Subject: Web Development using PHP & MySQL

Note that PHP is a loosely typed language, which means that variables can change their data type at
runtime based on the value they hold. For example, a variable that initially holds an integer value can be
changed to a string value later in the script.
Expressions and operators:
Expressions and operators are fundamental concepts in PHP programming. An expression is a
combination of variables, constants, functions, and operators that evaluate to a value. An operator is a
symbol that performs a specific operation on one or more values. Here are some examples of
expressions and operators in PHP:
Arithmetic operators: Arithmetic operators perform mathematical operations such as addition,
subtraction, multiplication, and division. Here are some examples:
// Addition operator
$sum = 10 + 5; // $sum equals 15

// Subtraction operator
$diff = 10 - 5; // $diff equals 5

// Multiplication operator
$product = 10 * 5; // $product equals 50

// Division operator
$quotient = 10 / 5; // $quotient equals 2

// Modulus operator
$remainder = 10 % 5; // $remainder equals 0
Comparison operators: Comparison operators compare two values and return a boolean value of true
or false. Here are some examples:
// Equal to operator
$is_equal = 10 == 5; // $is_equal equals false

// Not equal to operator


$is_not_equal = 10 != 5; // $is_not_equal equals true

// Greater than operator


$is_greater = 10 > 5; // $is_greater equals true

// Less than operator


$is_less = 10 < 5; // $is_less equals false

// Greater than or equal to operator


$is_greater_or_equal = 10 >= 5; // $is_greater_or_equal equals true

// Less than or equal to operator


$is_less_or_equal = 10 <= 5; // $is_less_or_equal equals false
Logical operators: Logical operators perform logical operations such as AND, OR, and NOT on
boolean values. Here are some examples:
// AND operator
$is_true = true;
7
Subject: Web Development using PHP & MySQL

$is_greater = 10 > 5;
$is_both_true = $is_true && $is_greater; // $is_both_true equals true

// OR operator
$is_false = false;
$is_less = 10 < 5;
$is_either_true = $is_false || $is_less; // $is_either_true equals false

// NOT operator
$is_not_true = !$is_true; // $is_not_true equals false
String operators: String operators perform string concatenation and string length operations. Here are
some examples:
// Concatenation operator
$first_name = "John";
$last_name = "Doe";
$full_name = $first_name . " " . $last_name; // $full_name equals "John Doe"

// String length operator


$name_length = strlen($full_name); // $name_length equals 8
These are just a few examples of expressions and operators in PHP. There are many more operators and
functions that you can use to perform various operations in your PHP code
Flow control Statements in PHP:
PHP Conditional Statements
Very often when you write code, you want to perform different actions for different conditions. You can
use conditional statements in your code to do this.
In PHP we have the following conditional statements:
 if statement - executes some code if one condition is true
 if...else statement - executes some code if a condition is true and another code if that condition is
false
 if...elseif...else statement - executes different codes for more than two conditions
 switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
The if statement executes some code if one condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
ExampleGet your own PHP Server
Output "Have a good day!" if the current time (HOUR) is less than 20:
<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
}
?>
PHP - The if...else Statement
8
Subject: Web Development using PHP & MySQL

The if...else statement executes some code if a condition is true and another code if that condition is
false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
Output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:
<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

PHP - The if...elseif...else Statement


The if...elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}

ExampleGet your own PHP Server


Output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current
time is less than 20. Otherwise it will output "Have a good night!":
<?php
$t = date("H");

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

The switch statement is used to perform different actions based on different conditions.
9
Subject: Web Development using PHP & MySQL

The PHP switch Statement


Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is evaluated once.
The value of the expression is then compared with the values for each case in the structure. If there is a
match, the block of code associated with that case is executed. Use break to prevent the code from
running into the next case automatically. The default statement is used if no match is found.
<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
PHP Loops
Often when you write code, you want the same block of code to run over and over again a certain
number of times. So, instead of adding several almost equal code-lines in a script, we can use loops.
Loops are used to execute the same block of code again and again, as long as a certain condition is true.
In PHP, we have the following loop types:
 while - loops through a block of code as long as the specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as the specified
condition is true
10
Subject: Web Development using PHP & MySQL

 for - loops through a block of code a specified number of times


 foreach - loops through a block of code for each element in an array
The following chapters will explain and give examples of each loop type.
The PHP while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
}
Examples
The example below displays the numbers from 1 to 5:
Example
<?php
$x = 1;

while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
The PHP do...while Loop
The do...while loop will always execute the block of code once, it will then check the condition, and
repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
Examples
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output,
and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?),
and the loop will continue to run as long as $x is less than, or equal to 5
ExampleGet your own PHP Server
<?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
The PHP for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:
11
Subject: Web Development using PHP & MySQL

 init counter: Initialize the loop counter value


 test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
 increment counter: Increases the loop counter value
Examples
The example below displays the numbers from 0 to 10:
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
The PHP foreach Loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.
Examples
The following example will output the values of the given array ($colors):
Example
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>
PHP Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to
"jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
This example jumps out of the loop when x is equal to 4:
Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
PHP Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.
12
Subject: Web Development using PHP & MySQL

This example skips the value of 4:


Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could
look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3
cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring to an
index number.
Get The Length of an Array - The count() Function
The count() function is used to return the length (the number of elements) of an array:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
PHP Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
The named keys can then be used in a script:

13
Subject: Web Development using PHP & MySQL

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Including html code with php:
You can include HTML code within PHP using the echo statement, which outputs text to the browser.
Here's an example:
<?php
echo "<html>";
echo "<head>";
echo "<title>My Page</title>";
echo "</head>";
echo "<body>";
echo "<h1>Welcome to my page</h1>";
echo "<p>This is some sample text.</p>";
echo "</body>";
echo "</html>";
?>
In this example, the PHP code outputs HTML tags to create a simple web page. The echo statement is
used to output each line of HTML code, enclosed in double quotes.
Alternatively, you can also use the shorthand syntax, called the short_open_tag, to directly include
HTML code within PHP tags. Here's an example:
<?php
// using short open tags
?>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Welcome to my page</h1>
<p>This is some sample text.</p>
</body>
</html>
<?php
// using short open tags
?>
In this example, the HTML code is included directly within the PHP tags. The <?php opening tag is
used to start the PHP code, and the ?> closing tag is used to end it. Between these tags, you can include
HTML code as you would in a regular HTML file
Embedding PHP in Web pages:
To embed PHP code in web pages, you need to save the file with a .php extension instead of .html.
Then you can include PHP code within HTML tags using the PHP opening and closing tags <?php and
?>.
Here's an example:
<!DOCTYPE html>
14
Subject: Web Development using PHP & MySQL

<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Welcome to my page</h1>
<p>Today's date is <?php echo date('Y-m-d'); ?></p>
<?php
// More PHP code can go here
?>
</body>
</html>
In this example, the PHP code is embedded within the HTML code using the opening <?php and
closing ?> tags. The echo statement within the PHP code outputs the current date in the Y-m-d format,
which is embedded within the <p> tag in the HTML code.
You can use PHP to dynamically generate HTML content based on data from databases, user input, or
other sources. For example, you can use PHP to create a login form that authenticates users, or to
generate a list of products from an online store. The possibilities are endless!

15
Subject: Web Development using PHP & MySQL

Unit 2
PHP Functions
PHP Built-in Functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to perform
a specific task.
Please check out our PHP reference for a complete overview of the PHP built-in functions.

PHP User Defined Functions


Besides the built-in PHP functions, it is possible to create your own functions.
A function is a block of statements that can be used repeatedly in a program.

A function will not execute automatically when a page loads.


A function will be executed by a call to the function.
Create a User Defined Function in PHP
A user-defined function declaration starts with the word function:
Syntax
function functionName()

{
code to be executed;
}

Example
<?php
function writeMsg() {
echo "Hello world!";
}

writeMsg(); // call the function


?>

PHP Function Arguments


Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.

16
Subject: Web Development using PHP & MySQL

The following example has a function with one argument ($fname). When the familyName()
function is called, we also pass along a name (e.g. Jani), and the name is used inside the function,
which outputs several different first names, but an equal last name:
Example

<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}

familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>

PHP Default Argument Value


The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument:
Example
<?php declare(strict_types=1); // strict requirement
function setHeight(int $minheight = 50) {
echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>

PHP Functions - Returning values


To let a function return a value, use the return statement:
Example
<?php declare(strict_types=1); // strict requirement
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
17
Subject: Web Development using PHP & MySQL

echo "5 + 10 = " . sum(5, 10) . "<br>";


echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>

PHP Return Type Declarations


PHP 7 also supports Type Declarations for the return statement. Like with the type declaration
for function arguments, by enabling the strict requirement, it will throw a "Fatal Error" on a type
mismatch.
To declare a type for the function return, add a colon ( : ) and the type right before the opening
curly ( { )bracket when declaring the function.
In the following example we specify the return type for the function:
Example
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>

PHP Date and Time


The PHP Date() Function
The PHP date() function formats a timestamp to a more readable date and time.

Get a Date
The required format parameter of the date() function specifies how to format the date (or time).
Here are some characters that are commonly used for dates:
d - Represents the day of the month (01 to 31)
m - Represents a month (01 to 12)
Y - Represents a year (in four digits)
l (lowercase 'L') - Represents the day of the week

Other characters, like"/", ".", or "-" can also be inserted between the characters to add additional
formatting.

18
Subject: Web Development using PHP & MySQL

The example below formats today's date in three different ways:

Example
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>

Get a Time
Here are some characters that are commonly used for times:
H - 24-hour format of an hour (00 to 23)
h - 12-hour format of an hour with leading zeros (01 to 12)
i - Minutes with leading zeros (00 to 59)

s - Seconds with leading zeros (00 to 59)


a - Lowercase Ante meridiem and Post meridiem (am or pm)
The example below outputs the current time in the specified format:
Example
<?php
echo "The time is " . date("h:i:sa");
?>

PHP hash() function:


PHP hash() function returns a string with lowercase hexits. If the raw_output is set to true, it will
return raw binary data.
PHP Version

This function will work from PHP Version greater than 5.1.2.
Example
To generate hash value using md5 Algorithm −

<?php

19
Subject: Web Development using PHP & MySQL

echo "The hash of Welcome to Tutorialspoint is - ". hash('md5', 'Welcome to Tutorialspoint');


?>
Output
This will produce the following result −
The hash of Welcome to Tutorialspoint is - 8ab923b97822bd258bf882e41de6ebff

PHP mail() Function


Definition and Usage
The mail() function allows you to send emails directly from a script.
ExampleGet your own PHP Server
Send a simple email:
<?php
// the message
$msg = "First line of text\nSecond line of text";

// use wordwrap() if lines are longer than 70 characters


$msg = wordwrap($msg,70);

// send email
mail("someone@[Link]","My subject",$msg);
?>

PHP PREDEFINED FUNCTIONS:


Functions are blocks of codes that perform specific task in php. It makes the codes reusable and
shorthand. it can be categorized into two groups.
Predefined functions are the inbuilt functions of php. These functions can be subdivided into
multiple categories as stated below.
string functions
numeric functions
date and time functions
array functions

20
Subject: Web Development using PHP & MySQL

directory functions
String Function
strtolower(); -> converts all characters of the string to lower case
strtoupper(); -> converts all characters of the string to upper case
ucfirst(); -> converts first letter to upper case

ucwords(); -> converts first letter of each word to upper case


strlen(); -> counts number of characters in a string and returns integer value
trim(); -> trims unnecessary spaces
ltrim(); -> trims unnecessary spaces from left
rtrim(); -> trims unnecessary spaces from right
sprintf("%s,%s,%s",$a,$b,$c); -> placeholder to keep the value

str_word_count() -> count the number of words


$count = str_word_count($x,1) -> returns array
strstr(); echo strstr($str,U,true);
stristr(); case insensitive strstr
str_replace() -> search and replace characters from the string
str_repeat() -> repeats the string

substr(int,int) -> prints a string from defined initial character number to defined last number
strpos() -> finds position of the string
Numeric Function
abs() -> returns positive value of a number
sqrt() -> returns square root of a number
round() -> rounds a floating number

floor() -> rounds a number down to a nearest integer


ceil() -> rounds a number up to a nearest integer
rand() -> generates a random integer
mt_rand() -> generates random number between defined inital and end number
21
Subject: Web Development using PHP & MySQL

pow() -> returns x raised to the power of y


pi() -> returns the value of pi
min() -> returns the lowest value from an array
max() -> returns the highest value from an array
fmod() -> returns the remainder from x/y {%}

bindec() -> converts a binary number to a decimal number


decbin() -> converts a decimal number to a binary number
Array Functions
array() -> creates an array
sizeof() -> counts the number of values in an array
sort() -> sorts an indexed array in ascending order

in_array() -> checks if a specified value is in array


list() -> keep array values in variable
compact() -> keeps variable values in associative array
arsort() -> sorts an associative array in descending order according to the value
array_unique() -> removes duplicate values from an array
explode() -> converts string to array

implode() -> converts array to string


extract() -> converts array to variable
array_sum() -> returns the sum of values in an array
array_shift() -> removes the first element of an array and returns the first value from the array
array_pop() -> deletes the last element from an array
array_merge() -> merges multiple arrays

array_search() -> searches for a defined value in an array and returns the key for that value
array_reverse() -> returns an array in reverse order
array_keys() -> returns all the keys from an array
Directory Functions
22
Subject: Web Development using PHP & MySQL

getcwd() -> get current working directory


mkdir() -> make directory
rmdir() -> remove directory
dirname() -> directory name
__DIR__ -> directory name

__FILE__ -> filename along with directory


__LINE__ -> line number
file_exists() -> checks if file exists and returns boolean value
unlink() -> remove file
is_file() -> boolean
is_dir() -> boolean

scan_dir() -> returns array of files present in the directory


file_size() -> returns file size in bytes
filectime() -> file created time (timestamps)
pathinfo() -> returns array / string based on arguments
copy() -> copy file
PHP Strings

A string is a sequence of characters, like "Hello world!".

PHP String Functions


In this chapter we will look at some commonly used functions to manipulate strings.

strlen() - Return the Length of a String

The PHP strlen() function returns the length of a string.


ExampleGet your own PHP Server
Return the length of the string "Hello world!":

23
Subject: Web Development using PHP & MySQL

<?php
echo strlen("Hello world!"); // outputs 12
?>
str_word_count() - Count Words in a String
The PHP str_word_count() function counts the number of words in a string.
ExampleGet your own PHP Server
Count the number of word in the string "Hello world!":

<?php
echo str_word_count("Hello world!"); // outputs 2
?> strrev() - Reverse a String
The PHP strrev() function reverses a string.
ExampleGet your own PHP Server
Reverse the string "Hello world!":
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>

strpos() - Search For a Text Within a String


The PHP strpos() function searches for a specific text within a string. If a match is found, the
function returns the character position of the first match. If no match is found, it will return
FALSE.
Example
Search for the text "world" in the string "Hello world!":
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>

str_replace() - Replace Text Within a String


The PHP str_replace() function replaces some characters with some other characters in a string.
Example
Replace the text "world" with "Dolly":

24
Subject: Web Development using PHP & MySQL

<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
PHP strcmp() Function
ExampleGet your own PHP Server
Compare two strings (case-sensitive):
<?php
echo strcmp("Hello world!","Hello world!");
?>

Encoding and Escaping


Because PHP programs often interact with HTML pages, web addresses (URLs), and databases,
there are functions to help you work with those types of data. HTML, web page addresses, and
database commands are all strings, but they each require different characters to be escaped in
different ways. For instance, a space in a web address must be written as %20, while a literal
less-than sign (<) in an HTML document must be written as &lt;. PHP has a number of built-in
functions to convert to and from these encodings.
HTML

Special characters in HTML are represented by entities such as &amp; and &lt;. There are two
PHP functions that turn special characters in a string into their entities: one for removing HTML
tags, and one for extracting only meta tags.
Entity-quoting all special characters
The htmlentities() function changes all characters with HTML entity equivalents into those
equivalents (with the exception of the space character). This includes the less-than sign (<), the
greater-than sign (>), the ampersand (&), and accented characters.
For example:
$string = htmlentities("Einstürzende Neubauten");
echo $string;
The htmlspecialchars() function converts the smallest set of entities possible to generate valid
HTML. The following entities are converted:
Ampersands (&) are converted to &amp;
Double quotes (") are converted to &quot;
Single quotes (') are converted to &#039; (if ENT_QUOTES is on, as described
for htmlentities())

25
Subject: Web Development using PHP & MySQL

Less-than signs (<) are converted to &lt;


Greater-than signs (>) are converted to &gt;
If you have an application that displays data that a user has entered in a form, you need to run
that data through htmlspecialchars() before displaying or saving it. If you don’t, and the user
enters a string like "angle < 30" or "sturm & drang", the browser will think the special characters
are HTML, resulting in a garbled page.
Like htmlentities(), htmlspecialchars() can take up to three arguments:
$output = htmlspecialchars(input, [quote_style, [charset]]);
The quote_style and charset arguments have the same meaning that they do for htmlentities().
There are no functions specifically for converting back from the entities to the original text,
because this is rarely needed. There is a relatively simple way to do this, though.
Use the get_html_translation_table() function to fetch the translation table used by either of these
functions in a given quote style. For example, to get the translation table that htmlentities() uses,
do this:
$table = get_html_translation_table(HTML_ENTITIES);

To get the table for htmlspecialchars() in ENT_NOQUOTES mode, use:


$table = get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES);
A nice trick is to use this translation table, flip it using array_flip(), and feed it to strtr() to apply
it to a string, thereby effectively doing the reverse of htmlentities():

$str = htmlentities("Einstürzende Neubauten"); // now it is encoded

$table = get_html_translation_table(HTML_ENTITIES);
$revTrans = array_flip($table);

echo strtr($str, $revTrans); // back to normal

Einstürzende Neubauten
You can, of course, also fetch the translation table, add whatever other translations you want to
it, and then do the strtr(). For example, if you wanted htmlentities() to also encode spaces
to &nbsp;s, you would do:
$table = get_html_translation_table(HTML_ENTITIES);
$table[' '] = '&nbsp;';

26
Subject: Web Development using PHP & MySQL

$encoded = strtr($original, $table);


Removing HTML tags
The strip_tags() function removes HTML tags from a string:
$input = '<p>Howdy, &quot;Cowboy&quot;</p>';
$output = strip_tags($input);

// $output is 'Howdy, &quot;Cowboy&quot;'


The function may take a second argument that specifies a string of tags to leave in the string. List
only the opening forms of the tags. The closing forms of tags listed in the second parameter are
also preserved:
$input = 'The <b>bold</b> tags will <i>stay</i><p>';
$output = strip_tags($input, '<b>');
// $output is 'The <b>bold</b> tags will stay'
Attributes in preserved tags are not changed by strip_tags(). Because attributes such
as style and onmouseover can affect the look and behavior of web pages, preserving some tags
with strip_tags() won’t necessarily remove the potential for abuse.

Extracting meta tags


The get_meta_tags() function returns an array of the meta tags for an HTML page, specified as a
local filename or URL. The name of the meta tag (keywords, author, description, etc.) becomes
the key in the array, and the content of the meta tag becomes the corresponding value:
$metaTags = get_meta_tags('[Link]
echo "Web page made by {$metaTags['author']}";

Web page made by John Doe


The general form of the function is:

$array = get_meta_tags(filename [, use_include_path]);


Pass a true value for use_include_path to let PHP attempt to open the file using the standard
include path.
URLs
PHP provides functions to convert to and from URL encoding, which allows you to build and
decode URLs. There are actually two types of URL encoding, which differ in how they treat
spaces. The first (specified by RFC 3986) treats a space as just another illegal character in a URL

27
Subject: Web Development using PHP & MySQL

and encodes it as %20. The second (implementing the application/x-www-form-


urlencoded system) encodes a space as a + and is used in building query strings.
Note that you don’t want to use these functions on a complete URL, such
as [Link] as they will escape the colons and slashes to produce:
http%3A%2F%[Link]%2Fhello
Only encode partial URLs (the bit after [Link] and add the protocol and
domain name later.
RFC 3986 encoding and decoding
To encode a string according to the URL conventions, use rawurlencode():
$output = rawurlencode(input);
This function takes a string and returns a copy with illegal URL characters encoded in
the %dd convention.
If you are dynamically generating hypertext references for links in a page, you need to convert
them with rawurlencode():
$name = "Programming PHP";
$output = rawurlencode($name);
echo "[Link]

[Link]
The rawurldecode() function decodes URL-encoded strings:

$encoded = 'Programming%20PHP';
echo rawurldecode($encoded);

Programming PHP
Query-string encoding
The urlencode() and urldecode() functions differ from their raw counterparts only in that they
encode spaces as plus signs (+) instead of as the sequence %20. This is the format for building
query strings and cookie values. These functions can be useful in supplying form-like URLs in
the HTML. PHP automatically decodes query strings and cookie values, so you don’t need to use
these functions to process those values. The functions are useful for generating query strings:
$baseUrl = '[Link]
$query = 'PHP sessions -cookies';

$url = $baseUrl . urlencode($query);


28
Subject: Web Development using PHP & MySQL

echo $url;

[Link]
SQL
Most database systems require that string literals in your SQL queries be escaped. SQL’s
encoding scheme is pretty simple—single quotes, double quotes, NUL-bytes, and backslashes
need to be preceded by a backslash. The addslashes() function adds these slashes, and
the stripslashes() function removes them:
$string = <<< EOF
"It's never going to work," she cried,
as she hit the backslash (\) key.
EOF;

$string = addslashes($string);
echo $string;
echo stripslashes($string);

\"It\'s never going to work,\" she cried,


as she hit the backslash (\\) key.
"It's never going to work," she cried,

as she hit the backslash (\) key.


PHP Regular Expressions
What is a Regular Expression?
A regular expression is a sequence of characters that forms a search pattern. When you search for
data in a text, you can use this search pattern to describe what you are searching for.
A regular expression can be a single character, or a more complicated pattern.
Regular expressions can be used to perform all types of text search and text replace operations.
Syntax
In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers.
$exp = "/w3schools/i";
In the example above, / is the delimiter, w3schools is the pattern that is being searched for,
and i is a modifier that makes the search case-insensitive.
29
Subject: Web Development using PHP & MySQL

The delimiter can be any character that is not a letter, number, backslash or space. The most
common delimiter is the forward slash (/), but when your pattern contains forward slashes it is
convenient to choose other delimiters such as # or ~.
Regular Expression Functions
PHP provides a variety of functions that allow you to use regular expressions.
The preg_match(), preg_match_all() and preg_replace() functions are some of the most
commonly used ones:

Function Description

preg_match() Returns 1 if the pattern was found in the string and 0 if not

preg_match_all() Returns the number of times the pattern was found in the string, which may also be 0

preg_replace() Returns a new string where matched patterns have been replaced with another string

Using preg_match()

The preg_match() function will tell you whether a string contains matches of a pattern.
ExampleGet your own PHP Server
Use a regular expression to do a case-insensitive search for "w3schools" in a string:
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str); // Outputs 1
?>
Using preg_match_all()
The preg_match_all() function will tell you how many matches were found for a pattern in a
string.
Example
Use a regular expression to do a case-insensitive count of the number of occurrences of "ain" in a
string:
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // Outputs 4
?>

30
Subject: Web Development using PHP & MySQL

Regular Expression Patterns


Brackets are used to find a range of characters:

Expression Description

[abc] Find one character from the options between the brackets

[^abc] Find any character NOT between the brackets

[0-9] Find one character from the range 0 to 9

Metacharacters
Metacharacters are characters with a special meaning:

Metacharacter Description

| Find a match for any one of the patterns separated by | as in: cat|dog|fish

. Find just one instance of any character

^ Finds a match as the beginning of a string as in: ^Hello

$ Finds a match at the end of the string as in: World$

\d Find a digit

\s Find a whitespace character

\b Find a match at the beginning of a word like this: \bWORD, or at the end of a word
like this: WORD\b

\uxxxx Find the Unicode character specified by the hexadecimal number xxxx

Quantifiers
Quantifiers define quantities:

Quantifier Description

31
Subject: Web Development using PHP & MySQL

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n

n? Matches any string that contains zero or one occurrences of n

n{x} Matches any string that contains a sequence of X n's

n{x,y} Matches any string that contains a sequence of X to Y n's

n{x,} Matches any string that contains a sequence of at least X n's

32
Subject: Web Development using PHP & MySQL

Unit 3
PHP Global Variables - Superglobals
Superglobals were introduced in PHP 4.1.0, and are built-in variables that are always available in
all scopes.

PHP Global Variables - Superglobals


Some predefined variables in PHP are "superglobals", which means that they are always
accessible, regardless of scope - and you can access them from any function, class or file without
having to do anything special.
The PHP superglobal variables are:
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
The next chapters will explain some of the superglobals, and the rest will be explained in later
chapters.
PHP Superglobal - $GLOBALS
Super global variables are built-in variables that are always available in all scopes.

PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables from
anywhere in the PHP script (also from within functions or methods).
PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name
of the variable.
The example below shows how to use the super global variable $GLOBALS:
Example
<?php
$x = 75;
$y = 25;

function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}

addition();
echo $z;
?>
PHP Superglobal - $_SERVER
Super global variables are built-in variables that are always available in all scopes.

PHP $_SERVER
33
Subject: Web Development using PHP & MySQL

$_SERVER is a PHP super global variable which holds information about headers, paths, and
script locations.
The example below shows how to use some of the elements in $_SERVER:
Example
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
The following table lists the most important elements that can go inside $_SERVER:
Element/Code Description
$_SERVER['PHP_SELF'] Returns the filename of the currently executing script
$_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common Gateway Interface (CGI)
the server is using
$_SERVER['SERVER_ADDR'] Returns the IP address of the host server
$_SERVER['SERVER_NAME'] Returns the name of the host server (such as
[Link])
$_SERVER['SERVER_SOFTWARE'] Returns the server identification string (such as
Apache/2.2.24)
$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the information protocol
(such as HTTP/1.1)
$_SERVER['REQUEST_METHOD'] Returns the request method used to access the page (such as
POST)
$_SERVER['REQUEST_TIME'] Returns the timestamp of the start of the request (such as
1377687496)
$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a query
string
$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request
$_SERVER['HTTP_ACCEPT_CHARSET'] Returns the Accept_Charset header from the current request
(such as utf-8,ISO-8859-1)

34
Subject: Web Development using PHP & MySQL

$_SERVER['HTTP_HOST'] Returns the Host header from the current request


$_SERVER['HTTP_REFERER'] Returns the complete URL of the current page (not reliable
because not all user-agents support it)
$_SERVER['HTTPS'] Is the script queried through a secure HTTP protocol
$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the
current page
$_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing the
current page
$_SERVER['REMOTE_PORT'] Returns the port being used on the user's machine to
communicate with the web server
$_SERVER['SCRIPT_FILENAME'] Returns the absolute pathname of the currently executing
script
$_SERVER['SERVER_ADMIN'] Returns the value given to the SERVER_ADMIN directive in
the web server configuration file (if your script runs on a
virtual host, it will be the value defined for that virtual host)
(such as someone@[Link])
$_SERVER['SERVER_PORT'] Returns the port on the server machine being used by the web
server for communication (such as 80)
$_SERVER['SERVER_SIGNATURE'] Returns the server version and virtual host name which are
added to server-generated pages
$_SERVER['PATH_TRANSLATED'] Returns the file system based path to the current script
$_SERVER['SCRIPT_NAME'] Returns the path of the current script
$_SERVER['SCRIPT_URI'] Returns the URI of the current page
Super global variables are built-in variables that are always available in all scopes.

PHP $_REQUEST
PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting
an HTML form.
The example below shows a form with an input field and a submit button. When a user submits
the data by clicking on "Submit", the form data is sent to the file specified in the action attribute
of the <form> tag. In this example, we point to this file itself for processing form data. If you
wish to use another PHP file to process form data, replace that with the filename of your choice.
Then, we can use the super global variable $_REQUEST to collect the value of the input field:
Example
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


35
Subject: Web Development using PHP & MySQL

Name: <input type="text" name="fname">


<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>

</body>
</html>
PHP $_POST
PHP $_POST is a PHP super global variable which is used to collect form data after submitting
an HTML form with method="post". $_POST is also widely used to pass variables.
The example below shows a form with an input field and a submit button. When a user submits
the data by clicking on "Submit", the form data is sent to the file specified in the action attribute
of the <form> tag. In this example, we point to the file itself for processing form data. If you
wish to use another PHP file to process form data, replace that with the filename of your choice.
Then, we can use the super global variable $_POST to collect the value of the input field:
Example
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
36
Subject: Web Development using PHP & MySQL

</body>
</html>
PHP $_GET
PHP $_GET is a PHP super global variable which is used to collect form data after submitting an
HTML form with method="get".
$_GET can also collect data sent in the URL.
Assume we have an HTML page that contains a hyperlink with parameters:
<html>
<body>

<a href="test_get.php?subject=PHP&web=[Link]">Test $GET</a>

</body>
</html>
When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to
"test_get.php", and you can then access their values in "test_get.php" with $_GET.
The example below shows the code in "test_get.php":
Example
<html>
<body>

<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>

</body>
</html>

PHP $_FILES:
The global predefined variable $_FILES is an associative array containing items uploaded via
HTTP POST method. Uploading a file requires HTTP POST method form with enctype attribute
set to multipart/form-data.
$HTTP_POST_FILES also contains the same information, but is not a superglobal, and now
been deprecated
The _FILES array contains following properties −
$_FILES['file']['name'] - The original name of the file to be uploaded.
$_FILES['file']['type'] - The mime type of the file.
$_FILES['file']['size'] - The size, in bytes, of the uploaded file.
$_FILES['file']['tmp_name'] - The temporary filename of the file in which the uploaded file
was stored on the server.
$_FILES['file']['error'] - The error code associated with this file upload.
Following [Link] contains a HTML form whose enctype is set to multiform/form-data. It also
has an input file element which presents a button on the form for the user to select file to be
uploaded.
<form action="[Link]" method="POST" enctype="multipart/form-data">
37
Subject: Web Development using PHP & MySQL

<input type="file" name="file">


<input type ="submit" value="submit">
</form>
The PHP script is as follows:
Example
<?php
echo "Filename: " . $_FILES['file']['name']."<br>";
echo "Type : " . $_FILES['file']['type'] ."<br>";
echo "Size : " . $_FILES['file']['size'] ."<br>";
echo "Temp name: " . $_FILES['file']['tmp_name'] ."<br>";
echo "Error : " . $_FILES['file']['error'] . "<br>";
?>
PHP $_ENV
$_ENV is another superglobal associative array in PHP. It stores environment variables available
to current script. $HTTP_ENV_VARS also contains the same information, but is not a
superglobal, and now been deprecated.
Environment variables are imported into global namespace. Most of these variables are provided
by the shell under which PHP parser is running. Hence, list of environment variables may be
different on different platforms.
This array also includes CGI variables in case whether PHP is running as a server module orCGI
processor.
PHP library has getenv()function to retrieve list of all environment variables or value of a
specific environment variable
getenv
Following script displays values of all available environment variables
<?php
$arr=getenv();
foreach ($arr as $key=>$val)
echo "$key=>$val
";
?>
PHP Form Validation
PHP Form Validation
Think SECURITY when processing PHP forms!
These pages will show how to process PHP forms with security in mind. Proper validation of
form data is important to protect your form from hackers and spammers!
The HTML form we will be working at in these chapters, contains various input fields: required
and optional text fields, radio buttons, and a submit button:

38
Subject: Web Development using PHP & MySQL

The validation rules for the form above are as follows:


Field Validation Rules
Name Required. + Must only contain letters and whitespace
E-mail Required. + Must contain a valid email address (with @ and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one
Text Fields
The name, email, and website fields are text input elements, and the comment field is a textarea.
The HTML code looks like this:
Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other

The Form Element


The HTML code of the form looks like this:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Big Note on PHP Form Security


The $_SERVER["PHP_SELF"] variable can be used by hackers!
If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site
Scripting (XSS) commands to execute.

39
Subject: Web Development using PHP & MySQL

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in


Web applications. XSS enables attackers to inject client-side script into Web pages viewed
by other users.
Assume we have the following form in a page named "test_form.php":
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Now, if a user enters the normal URL in the address bar like
"[Link] the above code will be translated to:
<form method="post" action="test_form.php">
So far, so good.
However, consider that a user enters the following URL in the address bar:
[Link]
In this case, the above code will be translated to:
<form method="post" action="test_form.php/"><script>alert('hacked')</script>
This code adds a script tag and an alert command. And when the page loads, the JavaScript code
will be executed (the user will see an alert box). This is just a simple and harmless example how
the PHP_SELF variable can be exploited.
Be aware of that any JavaScript code can be added inside the <script> tag! A hacker can
redirect the user to a file on another server, and that file can hold malicious code that can alter
the global variables or submit the form to another address to save the user data, for example.

How To Avoid $_SERVER["PHP_SELF"] Exploits?


$_SERVER["PHP_SELF"] exploits can be avoided by using the htmlspecialchars() function.
The form code should look like this:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
The htmlspecialchars() function converts special characters to HTML entities. Now if the user
tries to exploit the PHP_SELF variable, it will result in the following output:
<form method="post" action="test_form.php/&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script
&gt;">
The exploit attempt fails, and no harm is done!

Validate Form Data With PHP


The first thing we will do is to pass all variables through PHP's htmlspecialchars() function.
When we use the htmlspecialchars() function; then if a user tries to submit the following in a text
field:
<script>[Link]('[Link]
- this would not be executed, because it would be saved as HTML escaped code, like this:
&lt;script&gt;[Link]('[Link]
The code is now safe to be displayed on a page or inside an e-mail.
We will also do two more things when the user submits the form:
Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP
trim() function)
Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
The next step is to create a function that will do all the checking for us (which is much more
convenient than writing the same code over and over again).
We will name the function test_input().

40
Subject: Web Development using PHP & MySQL

Now, we can check each $_POST variable with the test_input() function, and the script looks
like this:
Example:
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
PHP Output Control Functions
PHP Output Control Functions
PHP provides a set of functions that control what content is sent to the browser and when. This is
referred to as output control.

Output can come from any of the following sources:

echo, print, printf, print_r... and other similar functions and statements
Notices, warnings and errors from PHP
Any content outside of the <?php ?> tags
PHP and the backend on which it is running may hold the output in a buffer before sending it to
the user.

Note: The output control functions can create any number of output buffers. Output buffers catch
output given by the program. Each new output buffer is placed on the top of a stack of output
buffers, and any output it provides will be caught by the buffer below it. The output control
functions handle only the topmost buffer, so the topmost buffer must be removed in order to
control the buffers below it.

Installation
The PHP output control functions are part of the PHP core. No installation is required to use
these functions.

Runtime Configuration
41
Subject: Web Development using PHP & MySQL

What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.

Create Cookies With PHP


A cookie is created with the setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.

PHP Create/Retrieve a Cookie


The following example creates a cookie named "user" with the value "John Doe". The cookie
will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire
website (otherwise, select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also
use the isset() function to find out if the cookie is set:
ExampleGet your own PHP Server
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>
PHP Sessions
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.

What is a PHP Session?


When you work with an application, you open it, do some changes, and then you close it. This is
much like a Session. The computer knows who you are. It knows when you start the application

42
Subject: Web Development using PHP & MySQL

and when you end. But on the internet there is one problem: the web server does not know who
you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple pages
(e.g. username, favorite color, etc). By default, session variables last until the user closes the
browser.
So; Session variables hold information about one single user, and are available to all pages in
one application.
Start a PHP Session
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP
session and set some session variables:
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

Get PHP Session Variable Values


Next, we create another page called "demo_session2.php". From this page, we will access the
session information we set on the first page ("demo_session1.php").
Notice that session variables are not passed individually to each new page, instead they are
retrieved from the session we open at the beginning of each page (session_start()).
Also notice that all session variable values are stored in the global $_SESSION variable:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
43
Subject: Web Development using PHP & MySQL

// Echo session variables that were set on previous page


echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</body>
</html>
Another way to show all the session variable values for a user session is to run the following
code:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
print_r($_SESSION);
?>

</body>
</html>
PHP File Handling
File handling is an important part of any web application. You often need to open and process a
file for different tasks.

PHP Manipulating Files


PHP has several functions for creating, reading, uploading, and editing files.
Be careful when manipulating files!
When you are manipulating files you must be very careful.
You can do a lot of damage if you do something wrong. Common errors are: editing the wrong
file, filling a hard-drive with garbage data, and deleting the content of a file by accident.

PHP readfile() Function


The readfile() function reads a file and writes it to the output buffer.
Assume we have a text file called "[Link]", stored on the server, that looks like this:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
The PHP code to read the file and write it to the output buffer is as follows
(the readfile() function returns the number of bytes read on success):
44
Subject: Web Development using PHP & MySQL

Example
<?php
echo readfile("[Link]");
?>
PHP File Open/Read/Close
PHP Open File - fopen()
A better method to open files is with the fopen() function. This function gives you more options
than the readfile() function.
We will use the text file, "[Link]", during the lessons:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
The first parameter of fopen() contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened. The following example also
generates a message if the fopen() function is unable to open the specified file:
ExampleGet your own PHP Server
<?php
$myfile = fopen("[Link]", "r") or die("Unable to open file!");
echo fread($myfile,filesize("[Link]"));
fclose($myfile);
?>
Tip: The fread() and the fclose() functions will be explained below.
The file may be opened in one of the following modes:
Modes Description

r Open a file for read only. File pointer starts at the beginning of the file

w Open a file for write only. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file

a Open a file for write only. The existing data in file is preserved. File pointer starts at
the end of the file. Creates a new file if the file doesn't exist

45
Subject: Web Development using PHP & MySQL

x Creates a new file for write only. Returns FALSE and an error if file already exists

r+ Open a file for read/write. File pointer starts at the beginning of the file

w+ Open a file for read/write. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file

a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at
the end of the file. Creates a new file if the file doesn't exist

x+ Creates a new file for read/write. Returns FALSE and an error if file already exists

PHP File Upload


With PHP, it is easy to upload files to the server.
However, with ease comes danger, so always be careful when allowing file uploads!

Configure The "[Link]" File


First, ensure that PHP is configured to allow file uploads.
In your "[Link]" file, search for the file_uploads directive, and set it to On:
file_uploads = On

Create The HTML Form


Next, create an HTML form that allow users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>

<form action="[Link]" method="post" enctype="multipart/form-data">


Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>
PHP Download File
PHP enables you to download file easily using built-in readfile() function. The readfile() function
reads a file and writes it to the output buffer.

46
Subject: Web Development using PHP & MySQL

PHP readfile() function


Syntax
int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )
$filename: represents the file name
$use_include_path: it is the optional parameter. It is by default false. You can set it to true to the
search the file in the included_path.
$context: represents the context stream resource.
int: it returns the number of bytes read from the file.
PHP Download File Example: Text File
File: [Link]
<?php
$file_url = '[Link]
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: utf-8");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
?>

47
Subject: Web Development using PHP & MySQL

UNIT 4
MySQL - Introduction
What is a Database?
A database is a separate application that stores a collection of data. Each database has one or
more distinct APIs for creating, accessing, managing, searching and replicating the data it holds.
Other kinds of data stores can also be used, such as files on the file system or large hash tables in
memory but data fetching and writing would not be so fast and easy with those type of systems.
Nowadays, we use relational database management systems (RDBMS) to store and manage huge
volume of data. This is called relational database because all the data is stored into different
tables and relations are established using primary keys or other keys known as Foreign Keys.
A Relational DataBase Management System (RDBMS) is a software that −
Enables you to implement a database with tables, columns and indexes.
Guarantees the Referential Integrity between rows of various tables.
Updates the indexes automatically.
Interprets an SQL query and combines information from various tables.
RDBMS Terminology
Before we proceed to explain the MySQL database system, let us revise a few definitions related
to the database.
Database − A database is a collection of tables, with related data.
Table − A table is a matrix with data. A table in a database looks like a simple spreadsheet.
Column − One column (data element) contains data of one and the same kind, for example the
column postcode.
Row − A row (= tuple, entry or record) is a group of related data, for example the data of one
subscription.
Redundancy − Storing data twice, redundantly to make the system faster.
Primary Key − A primary key is unique. A key value can not occur twice in one table. With a
key, you can only find one row.
Foreign Key − A foreign key is the linking pin between two tables.
Compound Key − A compound key (composite key) is a key that consists of multiple columns,
because one column is not sufficiently unique.
Index − An index in a database resembles an index at the back of a book.
Referential Integrity − Referential Integrity makes sure that a foreign key value always points to
an existing row.
MySQL Database
MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL is
developed, marketed and supported by MySQL AB, which is a Swedish company. MySQL is
becoming so popular because of many good reasons −
MySQL is released under an open-source license. So you have nothing to pay to use it.
MySQL is a very powerful program in its own right. It handles a large subset of the functionality
of the most expensive and powerful database packages.
MySQL uses a standard form of the well-known SQL data language.
MySQL works on many operating systems and with many languages including PHP, PERL, C,
C++, JAVA, etc.
MySQL works very quickly and works well even with large data sets.
MySQL is very friendly to PHP, the most appreciated language for web development.

48
Subject: Web Development using PHP & MySQL

MySQL supports large databases, up to 50 million rows or more in a table. The default file size
limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a
theoretical limit of 8 million terabytes (TB).
MySQL is customizable. The open-source GPL license allows programmers to modify the
MySQL software to fit their own specific environments.
Introduction to SQL
What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in 1987
What Can SQL do?
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and views

SQL is a Standard - BUT....


Although SQL is an ANSI/ISO standard, there are different versions of the SQL language.
However, to be compliant with the ANSI standard, they all support at least the major commands
(such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner.
Note: Most of the SQL database programs also have their own proprietary extensions in addition
to the SQL standard!

Using SQL in Your Web Site


To build a web site that shows data from a database, you will need:
An RDBMS database program (i.e. MS Access, SQL Server, MySQL)
To use a server-side scripting language, like PHP or ASP
To use SQL to get the data you want
To use HTML / CSS to style the page
RDBMS
RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM
DB2, Oracle, MySQL, and Microsoft Access.
The data in RDBMS is stored in database objects called tables. A table is a collection of related
data entries and it consists of columns and rows.
Look at the "Customers" table:
Exampl
SELECT * FROM Customers;

49
Subject: Web Development using PHP & MySQL

Every table is broken up into smaller entities called fields. The fields in the Customers table
consist of CustomerID, CustomerName, ContactName, Address, City, PostalCode and Country.
A field is a column in a table that is designed to maintain specific information about every record
in the table.
A record, also called a row, is each individual entry that exists in a table. For example, there are
91 records in the above Customers table. A record is a horizontal entity in a table.
A column is a vertical entity in a table that contains all information associated with a specific
field in a table.
phpMyAdmin
phpMyAdmin is an open-source software tool introduced on September 9, 1998, which is
written in PHP. Basically, it is a third-party tool to manage the tables and data inside the
database. phpMyAdmin supports various type of operations on MariaDB and MySQL. The
main purpose of phpMyAdmin is to handle the administration of MySQL over the web.
It is the most popular application for MySQL database management. We can create, update,
drop, alter, delete, import, and export MySQL database tables by using this software.
phpMyAdmin also supports a wide range of operation like managing databases, relations,
tables, columns, indexes, permissions, and users, etc., on MySQL and MariaDB. These
operations can be performed via user interface, while we still have the ability to execute any
SQL statement.
phpMyAdmin is translated into 72 languages and also supports both RTL and LTR
languages so that the wide range of people can easily use this software. We can run MySQL
queries, repair, optimized, check tables, and also execute other database management commands.
phpMyAdmin can also be used to perform administrative tasks such as database creation,
query execution.
phpMyAdmin is a GUI-based application which is used to manage MySQL database. We can
manually create database and table and execute the query on them. It provides a web-based
interface and can run on any server. Since it is web-based, so we can access it from any
computer.
Features of phpMyAdmin
phpMyAdmin supports several features that are given below:
phpMyAdmin can create, alter, browse, and drop databases, views, tables, columns, and indexes.
It can display multiple results sets through queries and stored procedures.
phpMyAdmin use stored procedure and queries to display multiple results sets.
It supports foreign keys and InnoDB tables.
phpMyAdmin can track the changes done on databases, views, and tables.
We can also create PDF graphics of our database layout.
phpMyAdmin can be exported into various formats such as XML, CSV, PDF, ISO/IEC 26300 -
OpenDocument Text and Spreadsheet.
It supports mysqli, which is the improved MySQL extension.
phpMyAdmin can interact with 80 different languages.
phpMyAdmin can edit, execute, and bookmark any SQL-statements and even batch-queries.
By using a set of pre-defined functions, it can transform stored data into any format. For
example - BLOB-data as image or download-link.
It provides the facility to backup the database into different forms.
Advantage of phpMyAdmin
phpMyAdmin can run on any server or any OS as it has a web browser.
50
Subject: Web Development using PHP & MySQL

We can easily create, delete, and edit the database and can manage all elements using
the graphical interface of phpMyAdmin, which is much easier than MySQL command-line
editor.
phpMyAdmin helps us to control the user's permission and operate several servers at the same
time.
We can also backup our database and export the data into different formats like XML, CSV,
SQL, PDF, OpenDocument Text, Excel, Word, and Spreadsheet, etc.
We can execute complex SQL statements and queries, create and edit functions, triggers, and
events using the graphical interface of phpMyAdmin.
Disadvantage of phpMyAdmin
phpMyAdmin is a simple interface, but quite tough for a beginner to learn.
phpMyAdmin is difficult to install as it needs three more software tools before installation,
which is- Apache server, PHP, and MySQL.
We have to install all these software tools individually, whereas XAMPP already contains them
in a single package. XAMPP is the easiest way to get phpMyAdmin.
It has no schema visualization.
phpMyAdmin is a web-based software tool which runs only on the browser, so It completely
depends on browsers.
It does not have auto-compilation capability.
Data Backup problem with phpMyAdmin
phpMyAdmin lacks a lot of features in import/export functionality. There are some backup
problems with phpMyAdmin that are given below:
Scheduling - There is no way to export the data of the database in phpMyAdmin automatically.
Storage media support - As we have discussed earlier, phpMyAdmin is web-based software, so
it runs only on the browser. We can take backups only to local drives of our system.
Compression, Encryption, and other option - The files which are exported with phpMyAdmin
are saved as common text files, with any additional processing. Whereas storing these files in the
original form usually takes a lot of disk storage.
Create a New Database in phpMyAdmin
We have seen many apps uses any specific backend database or services which are used to
store data of the app within itself. In this article we will take a look on creating a new SQL
database in phpMyAdmin so that we can perform CRUD operations using that database.
In this article we will be simply setting our SQL database in which we will be performing
CRUD operations through our Android Applications. For this, we will be creating a database
using XAMPP on localhost.
Prerequisites : You should be having XAMPP installed on your system so that we can open
phpMyAdmin and run it on local server.
Step 1 : Start your XAMPP server as shown in below screen
For starting your server on Xampp, we simply have to start the services in the Xampp console
which is shown on below screenshot.

51
Subject: Web Development using PHP & MySQL

After starting this services type localhost in your search bar and a page will open. On this page
click on phpMyAdmin option .
Step 2 : Creating a new database
Click on New option which is shown in below screen. After that we have to enter our database
name and then click on Create option to create a new database.
After creating a new database we have to move forward for creating a new SQL table.
Step 3 : Creating a new table for storing our data
After creating your database, see below screen. In this screen we will be creating a new table.
For creating a new table specify your table name and number of columns. In our case we are
specifying our table name as courseDb and specify the number of columns as 4. The 4 different
columns are as follows. The 1st column is for id, 2nd column is for courseName, 3rd column is
for courseDescription and 4th column is for courseDuration.
After clicking on Go option your table will be created. Now we have to add column heading
for our SQLite table. For adding this column heading you will get to see below screen.
Steps to Create the SQL table :
Enter the name for your columns in name section which is shown in above screen.
After that enter the datatype of the data which we will be adding in our database. In this we are
specifying INT for our ID as our ID will be an integer. And in SQL table VARCHAR is used
for storing strings.
In the length/ values section we have to specify the maximum length of the data which we will
be adding in our table. We will not be specifying length for our ID because it is added
automatically.
After that we have to auto increment our ID. For this we have to check the box which is shown
in above screenshot so that it will be incremented automatically on adding new data.
Now our database has been created successfully.
52
Subject: Web Development using PHP & MySQL

Deleting or dropping a table in phpMyAdmin


Log into your cPanel interface.
From the main cPanel screen, look for the Databases category and click on
the phpMyAdmin tool icon.

Once you are in the phpMyAdmin tool, find and click on the database name that contains the
table you want to drop.

After clicking the database name, the tables will be listed in the right hand panel. Locate the
table you want to drop and select the Drop link.
You will receive a popup. Click the OK button to confirm the delete.
You will receive a deletion success message and see your table disappear from the list. Below is
a quick before and after shot of the table list for a successful deletion.
Loading Data Into a Mysql Table With using phpMyAdmin
you can load data into a table in phpMyAdmin using the graphical user interface (GUI):
Open phpMyAdmin and select the database you want to work with.

53
Subject: Web Development using PHP & MySQL

Click on the table you want to load data into.

Click on the "Insert" tab at the top of the page.


In the "Values" section, enter the data you want to add to the table. Make sure to enter the values
in the correct format and order.
If the table has more than one column, click the "+" button to add another row for more values.
Once you've entered all the data you want to add, click the "Go" button at the bottom of the page.
If the data was inserted successfully, you should see a message indicating that the data was
added.
If you want to add more data, click the "Insert" tab again and repeat the process.
54
Subject: Web Development using PHP & MySQL

PHP MySQL Select/Retrieve Data


elect Data From a MySQL Database
The SELECT statement is used to select data from one or more tables:
SELECT column_name(s) FROM table_name
or we can use the * character to select ALL columns from a table:
SELECT * FROM table_name
Select Data With MySQLi
The following example selects the id, firstname and lastname columns from the MyGuests table
and displays it on the page:
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Code lines to explain from the example above:
First, we set up an SQL query that selects the id, firstname and lastname columns from the
MyGuests table. The next line of code runs the query and puts the resulting data into a variable
called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into an
associative array that we can loop through. The while() loop loops through the result set and
outputs the data from the id, firstname and lastname columns.
Sorting/Select and Order Data From a MySQL Database
The ORDER BY clause is used to sort the result-set in ascending or descending order.
55
Subject: Web Development using PHP & MySQL

The ORDER BY clause sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
Select and Order Data With MySQLi
The following example selects the id, firstname and lastname columns from the MyGuests table.
The records will be ordered by the lastname column:
Example (MySQLi Object-oriented)Get your own PHP Server
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Code lines to explain from the example above:
First, we set up the SQL query that selects the id, firstname and lastname columns from the
MyGuests table. The records will be ordered by the lastname column. The next line of code runs
the query and puts the resulting data into a variable called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into an
associative array that we can loop through. The while() loop loops through the result set and
outputs the data from the id, firstname and lastname columns.

56
Subject: Web Development using PHP & MySQL

UNIT 5
PHP MySQL Database
What is MySQL?
MySQL is a database system used on the web
MySQL is a database system that runs on a server
MySQL is ideal for both small and large applications
MySQL is very fast, reliable, and easy to use
MySQL uses standard SQL
MySQL compiles on a number of platforms
MySQL is free to download and use
MySQL is developed, distributed, and supported by Oracle Corporation
MySQL is named after co-founder Monty Widenius's daughter: My
The data in a MySQL database are stored in tables. A table is a collection of related data, and it
consists of columns and rows.
Databases are useful for storing information categorically. A company may have a database with
the following tables:
Employees
Products
Customers
Orders
PHP Connect to MySQL
PHP 5 and later can work with a MySQL database using:
MySQLi extension (the "i" stands for improved)
PDO (PHP Data Objects)
Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in
2012.

Should I Use MySQLi or PDO?


If you need a short answer, it would be "Whatever you like".
Both MySQLi and PDO have their advantages:
PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL
databases.
So, if you have to switch your project to use another database, PDO makes the process easy. You
only have to change the connection string and a few queries. With MySQLi, you will need to
rewrite the entire code - queries included.
Both are object-oriented, but MySQLi also offers a procedural API.
Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very
important for web application security.

MySQL Examples in Both MySQLi and PDO Syntax


In this, and in the following chapters we demonstrate three ways of working with PHP and
MySQL:
MySQLi (object-oriented)
MySQLi (procedural)
PDO

57
Subject: Web Development using PHP & MySQL

MySQLi Installation
For Linux and Windows: The MySQLi extension is automatically installed in most cases, when
php5 mysql package is installed
Open a Connection to MySQL
Before we can access data in the MySQL database, we need to be able to connect to the server:
Example (MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Note on the object-oriented example above:


$connect_error was broken until PHP 5.2.9 and 5.3.0. If you need to ensure compatibility with
PHP versions prior to 5.2.9 and 5.3.0, use the following code instead:

// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Example (PDO)
58
Subject: Web Development using PHP & MySQL

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>

Note: In the PDO example above we have also specified a database (myDB). PDO require a
valid database to connect to. If no database is specified, an exception is thrown.
Tip: A great benefit of PDO is that it has an exception class to handle any problems that may
occur in our database queries. If an exception is thrown within the try{ } block, the script stops
executing and flows directly to the first catch(){ } block.

Close the Connection


The connection will be closed automatically when the script ends. To close the connection
before, use the following:
MySQLi Object-Oriented:
$conn->close();

MySQLi Procedural:
mysqli_close($conn);

PDO:
$conn = null;

PHP MySQL Insert Data


Insert Data Into MySQL Using MySQLi and PDO
After a database and a table have been created, we can start adding data in them.
Here are some syntax rules to follow:
The SQL query must be quoted in PHP
String values inside the SQL query must be quoted
Numeric values must not be quoted
The word NULL must not be quoted
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
In the previous chapter we created an empty table named "MyGuests" with five columns: "id",
"firstname", "lastname", "email" and "reg_date". Now, let us fill the table with data.
59
Subject: Web Development using PHP & MySQL

Note: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP with default
update of current_timesamp (like the "reg_date" column), it is no need to be specified in the SQL
query; MySQL will automatically add the value.
The following examples add a new record to the "MyGuests" table:
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@[Link]')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
PHP MySQL Select Data
Select Data From a MySQL Database
The SELECT statement is used to select data from one or more tables:
SELECT column_name(s) FROM table_name
or we can use the * character to select ALL columns from a table:
SELECT * FROM table_name

Select Data With MySQLi


The following example selects the id, firstname and lastname columns from the MyGuests table
and displays it on the page:
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

60
Subject: Web Development using PHP & MySQL

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Code lines to explain from the example above:
First, we set up an SQL query that selects the id, firstname and lastname columns from the
MyGuests table. The next line of code runs the query and puts the resulting data into a variable
called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into an
associative array that we can loop through. The while() loop loops through the result set and
outputs the data from the id, firstname and lastname columns.
The following example shows the same as the example above, in the MySQLi procedural way:
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = mysqli_query($conn, $sql);

61
Subject: Web Development using PHP & MySQL

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>

PHP MySQL Delete Data


elete Data From a MySQL Table Using MySQLi and PDO
The DELETE statement is used to delete records from a table:
DELETE FROM table_name
WHERE some_column = some_value
Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which
record or records that should be deleted. If you omit the WHERE clause, all records will be
deleted!
Let's look at the "MyGuests" table:
id firstname lastname email reg_date
1 John Doe john@[Link] 2014-10-22 14:26:15
2 Mary Moe mary@[Link] 2014-10-23 10:22:30
3 Julie Dooley julie@[Link] 2014-10-26 10:48:23
The following examples delete the record with id=3 in the "MyGuests" table:
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

62
Subject: Web Development using PHP & MySQL

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

$conn->close();
?>
PHP MySQL Update Data
Update Data In a MySQL Table Using MySQLi and PDO
The UPDATE statement is used to update existing records in a table:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
Let's look at the "MyGuests" table:
id firstname lastname email reg_date
1 John Doe john@[Link] 2014-10-22 14:26:15
2 Mary Moe mary@[Link] 2014-10-23 10:22:30
The following examples update the record with id=2 in the "MyGuests" table:
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if ($conn->query($sql) === TRUE) {


echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

63
Subject: Web Development using PHP & MySQL

$conn->close();
?>

64

You might also like