PHP Chapter 2
PHP Chapter 2
Server-side programming
1
Server side scripting
• It is a web technology that allows custom HTML to be delivered to a client machine where the
code that generates processed on the web server
• Server-side language code remains on the web server. After it has been processed, the server sends
only the output of the script to the user as HTML format.
– ASP, PHP, … are examples of server side scripting languages
2
Fig.2.1. How Server side scripting work
5
What is a PHP File?
• PHP files can contain text, HTML, CSS,
JavaScript, and PHP code
• PHP code are executed on the server, and the
result is returned to the browser as plain
HTML
• PHP files have extension ".php"
6
What Can PHP Do?
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and
close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your
database
• PHP can be used to control user-access
• PHP can encrypt data
7
Why PHP?
• PHP runs on various platforms (Windows, Linux,
Unix, Mac OS X, etc.)
• PHP is compatible with almost all servers used
today (Apache, IIS, etc.)
• PHP supports a wide range of databases
• PHP is free. Download it from the official PHP
resource: www.php.net
• PHP is easy to learn and runs efficiently on the
server side
8
Use a Web Host With PHP Support
• If your server has activated support for PHP you
do not need to do anything.
• Just create some .php files, place them in your
web directory, and the server will automatically
parse them for you.
• You do not need to compile anything or install
any extra tools.
• Because PHP is free, most web hosts offer PHP
support.
9
Set Up PHP on Your Own PC
• However, if your server does not support PHP,
you must:
o install a web server
o install PHP
o install a database, such as MySQL
• The official PHP website (PHP.net) has
installation instructions for PHP:
http://php.net/manual/en/install.php
10
Basic PHP Syntax
• A PHP script is executed on the server, and the plain HTML
result is sent back to the browser.
• PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with ?>:
• <?php
// PHP code goes here
?>
<?php
echo "Hello World!";
?>
</body>
Note: PHP statements end with a semicolon (;).
</html>
12
Comments in PHP
• A comment in PHP code is a line that is not
read/executed as part of the program. Its only purpose
is to be read by someone who is looking at the code.
• Comments can be used to:
o Let others understand what you are doing
o Remind yourself of what you did - Most programmers have
experienced coming back to their own work a year or two
later and having to re-figure out what they did. Comments
can remind you of what you were thinking when you wrote
the code
• PHP supports several ways of commenting:
13
Example
• <!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body> 14
</html>
PHP Case Sensitivity
• In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and
user-defined functions are NOT case-sensitive.
• <!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
However; all variable names are case-
</html>
sensitive.
15
Cont…
• <!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
16
PHP Variables
• Variables are "containers" for storing information.
Creating (Declaring) PHP Variables
• In PHP, a variable starts with the $ sign, followed by the name
of the variable:
• <?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
Note: Unlike other programming languages, PHP has no
command for declaring a variable. It is created the moment
you first assign a value to it.
17
Cont…
• A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume).
• Rules for PHP variables:
• A variable starts with the $ sign, followed by the name of the
variable
• A variable name must start with a letter or the underscore
character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two
different variables)
Remember that PHP variable names are case-sensitive!
18
Output Variables
• The PHP echo statement is often used to output data to the
screen.
• <?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
The following example will produce the same output as the
example above:
• <?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
19
Cont…
• The following example will output the sum of
two variables:
• <?php
$x = 5;
$y = 4;
echo $x + $y;
?>
20
PHP is a Loosely Typed Language
• PHP automatically converts the variable to the
correct data type, depending on its value.
• In other languages such as C, C++, and Java,
the programmer must declare the name and
type of the variable before using it.
21
PHP Variables Scope
• In PHP, variables can be declared anywhere in
the script.
• The scope of a variable is the part of the script
where the variable can be referenced/used.
• PHP has three different variable scopes:
o Local
o Global
o static
22
Global and Local Scope
• A variable declared outside a function has a GLOBAL SCOPE
and can only be accessed outside a function:
• <?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
23
Cont…
• A variable declared within a function has a LOCAL SCOPE and can
only be accessed within that function:
• <?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
25
Cont…
• PHP also stores all global variables in an array called $GLOBALS[index].
The index holds the name of the variable.
• This array is also accessible from within functions and can be used to update global
variables directly.
• Example
• <?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
26
PHP The static Keyword
• Normally, when a function is completed/executed, all of its
variables are deleted.
• However, sometimes we want a local variable NOT to be deleted.
We need it for a further job.
• To do this, use the static keyword when you first declare the
variable:
• <?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest(); 27
?>
PHP Data Types
• Variables can store data of different types, and different
data types can do different things.
• PHP supports the following data types:
o String
o Integer
o Float (floating point numbers - also called double)
o Boolean
o Array
o Object
o NULL
o Resource
28
PHP String
• A string is a sequence of characters, like "Hello world!".
• A string can be any text inside quotes. You can use single
or double quotes:
• <?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
29
PHP Integer
• An integer data type is a non-decimal number
between -2,147,483,648 and 2,147,483,647.
• Rules for integers:
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in three formats: decimal
(10-based), hexadecimal (16-based - prefixed with
0x) or octal (8-based - prefixed with 0)
30
Cont…
• The PHP var_dump() function returns the data type and value:
• <?php
$x = 5985;
var_dump($x);
?>
PHP Float
• A float (floating point number) is a number with a decimal point
or a number in exponential form.
• <?php
$x = 10.365;
var_dump($x);
?>
31
PHP Boolean
• A Boolean represents two possible states: TRUE or FALSE.
• $x = true;
$y = false;
• Booleans are often used in conditional testing.
PHP Array
• An array stores multiple values in one single variable.
• <?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
32
PHP Object
• An object is a data type which stores data and
information on how to process that data.
• In PHP, an object must be explicitly declared.
• First we must declare a class of object. For
this, we use the class keyword.
• A class is a structure that can contain
properties and methods:
33
Cont…
• <?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
37
Constants are Global
• Constants are automatically global and can be used across the
entire script.
• The example below uses a constant inside a function, even if it is
defined outside the function:
• <?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();
?>
38
PHP Operators
• Operators are used to perform operations on
variables and values.
• PHP divides the operators in the following groups:
o Arithmetic operators
o Assignment operators
o Comparison operators
o Increment/Decrement operators
o Logical operators
o String operators
o Array operators
39
PHP Arithmetic Operators
• The PHP arithmetic operators are used with
numeric values to perform common
arithmetical operations, such as addition,
subtraction, multiplication etc.
40
• Assignment
• <!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
echo $x;
?>
</body>
</html>
41
Cont…
• <!DOCTYPE html>
<html>
<body>
<?php
$x = 20;
$x += 100;
echo $x;
?>
</body>
</html>
42
PHP Comparison Operators
• used to compare two values (number or
string):
43
Cont…
• <!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
$y = "100";
</body>
</html>
44
Cont…
• <!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
$y = "100";
var_dump($x === $y); // returns false because types are not equal
?>
</body>
</html>
45
Cont…
• <!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
$y = "100";
</body>
</html>
46
Cont…
• <!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
$y = "100";
</body>
</html>
47
PHP Increment / Decrement Operators
• The PHP increment operators are used to increment a
variable's value.
• The PHP decrement operators are used to decrement a
variable's value.
48
• <!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
echo ++$x;
?>
</body>
</html>
49
PHP Logical Operators
• The PHP logical operators are used to combine
conditional statements.
50
Cont…
• <!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
$y = 50;
</body>
</html>
51
Cont…
• // Not operator
• <!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
</body>
</html>
52
PHP String Operators
• PHP has two operators that are specially designed for strings.
• <!DOCTYPE html>
<html>
<body>
<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2;
?>
</body>
</html>
53
• <!DOCTYPE html>
<html>
<body>
<?php
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2;
echo $txt1;
?>
</body>
</html>
54
Conditional statements
Conditional statements like if, if…else and switch are supported
If statement
example
<? php
$number_three = 421;
if ( $number_three == 3 ) {
echo "The if statement evaluated to true";
}
else {
echo "The if statement evaluated to false";
}
?>
55
switch Statement
• The switch statement is used to perform different actions based on
different conditions.
• Use the switch statement to select one of many blocks of code to be
executed.
• 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;
}
56
Cont…
• 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.
57
Cont…
• <?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!";
}
?>
58
PHP Loops
• Often when you write code, you want the same block of code
to run over and over again in a row. Instead of adding several
almost equal code-lines in a script, we can use loops to perform
a task like this.
• In PHP, we have the following looping statements:
• 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
• 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
59
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;
}
• Example
• <?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
60
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);
• Example
• <?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
61
Cont…
• Notice that in a do while loop the condition is tested AFTER
executing the statements within the loop.
• This means that the do while loop would execute its statements at
least once, even if the condition is false the first time.
• <?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
62
The PHP for Loop
• PHP for loops execute a block of code a specified number of
times.
• 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;
}
• Parameters:
o init counter: Initialize the loop counter value
o test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the
loop continues. If it evaluates to FALSE, the loop ends.
o increment counter: Increases the loop counter value
63
Cont…
• <?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.
64
Cont…
• <?php
$colors
= array("red", "green", "blue", "yellow");
65
PHP Functions
66
Cont…
• <?php
function writeMsg() {
echo "Hello world!";
}
68
PHP Function Arguments
69
Cont…
• <?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
70
Cont…
• The following example has a function with two arguments
($fname and $year):
• <?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
71
PHP Default Argument Value
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
72
PHP Functions - Returning values
73
PHP Arrays
• 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.
Create an Array in PHP
• In PHP, the array() function is used to create an array:
• array();
75
Cont…
76
Cont…
77
Cont…
78
Cont…
• <?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
79
PHP Associative Arrays
80
Cont…
81
Cont…
• <?php
$age
= array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
82
PHP Sorting Arrays
• The elements in an array can be sorted in alphabetical or
numerical order, descending or ascending.
PHP - Sort Functions For Arrays
• sort() - sort arrays in ascending order
• rsort() - sort arrays in descending order
• asort() - sort associative arrays in ascending order, according to
the value
• ksort() - sort associative arrays in ascending order, according to
the key
• arsort() - sort associative arrays in descending order, according to
the value
• krsort() - sort associative arrays in descending order, according to
the key
83
Cont…
84
Cont…
• Sort Array in Descending Order - rsort()
• Example
• <?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>
• Sorts the elements of the $numbers array in descending
numerical order:
• Example
• <?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>
85
Cont…
86
Cont…
87
Cont…
88
Cont…
89
PHP Multidimensional Arrays
90
Cont…
91
Cont…
• We can also put a For loop inside another For loop to get the
elements of the $cars array (we still have to point to the two indices):
• Example
• <?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
94
OBJECT ORIENTED
PROGRAMMING IN PHP
95
What is object-oriented programming?
Classes
• A class is a blueprint for objects. It’s a chunk of code that
defines:
• The types of data that objects created from the class will store,
and
• The functions that those objects will contain.
97
Objects
99
Methods
100
How to create classes in PHP
• The basic syntax for creating a class in PHP looks like this:
class ClassName {
// (class definition goes here)
}
• For example, if you were creating a Member class for a web forums
application, you’d write:
class Member {
// (class definition goes here)
}
It’s good programming practice to put each class’s code in its own file,
with the same name as the class. For example, you might put the above
Member class code in a file called Member.php, and store the file in a folder
called classes.
101
How to create objects in PHP
102
Visibility (public, private, protected)
103
Cont…
108
Cont…
• Any further attempt to reset the $num property without the
setNum() method would result in a Fatal Error such as
Fatal error: Cannot access private property mathematics::
$num in /www/mathematics.class.php on line 43
Even if you were to try to access the private $num property
from a child class it would fail.
• This is because private methods and properties in a parent
class are not visible to child classes and cannot be accessed.
• To access a parent method or property from a child class you
need to use the protected keyword. Like the private keyword,
protected methods and properties are available only to the
class that created them.
• But unlike private, protected methods and properties are
visible from a parent class. Lets see how this works.
109
Cont…
<?php
class mathematics{
protected $num;
public function setNum($num){
$this->num = $num;
}
public function addTwo(){
return $this->num+2; }
}/*** end of class ***/
110
Cont…
class divide extends mathematics{
public function divideByTwo(){
/*** divide number by two ***/
$new_num = $this->num/2;
/*** return the new number and round to 2 decimal places ***/
return round($new_num, 2);
}
} /*** end of class ***/
/*** Instantiate a new class instance ***/
$math = new divide;
/*** set the value of the number ***/
$math->setNum(14);
echo $math->divideByTwo();
?>
111
Cont…
• We can see here the the user space code has called the
setNum() method in the parent mathematics class.
• This method, in turn, sets the $num property.
112
Accessing properties
• To access an object’s property you use the -> operator, as
follows:
$object->propertyName
<?php
class Member {
public $username = "";
}
$member = new Member();
$member->username = "Fred";
echo $member->username; // Displays "Fred“
?>
113
Adding methods to a class
• How about adding methods to a class?
• Methods are simply functions that are part of a class. So it probably comes
as no surprise that you create a method much like any other function — by
using the function keyword.
• The only difference is that you should also add public, private or protected
to the method definition, much as you do with properties:
class ClassName
{ public function methodName() {
// (Method's code here)
} private function methodName() {
// (Method's code here)
} protected function methodName() {
// (Method's code here)
}}
114
Cont…
• Note: As with properties
public methods can be called from anywhere
private methods can only be called by other methods in the
class, and
protected methods can be called by methods in the class and
in any derived classes.
115
Cont…
• Let’s try adding some methods to our Member class. We’ll
add:
• A private property called $loggedIn to record whether the
member is logged in or not
• A method called login() that logs the member in by setting
$loggedIn to true
• A method called logout() that logs the member out by setting
$loggedIn to false
• A method called isLoggedIn() that returns the value of
$loggedIn
116
Cont…
<?php
class Member
{
public $username = "";
private $loggedIn = false;
public function login() {
$this->loggedIn = true;
}
public function logout() {
$this->loggedIn = false;
}
public function isLoggedIn() {
return $this->loggedIn;
} } ?>
117
Cont…
• $this refers to the object itself.
• By using $this within an object’s method, the method can
access any of the other properties and methods in the object
• For example, the login() method accesses its object’s
$loggedIn property by using $this->loggedIn.
118
Using method
• To call an object’s method, you use your old friend,
the -> operator:
• $object->methodName() This works just like a
regular function call.
• You can pass arguments inside the parentheses
(assuming the method can accept arguments), and the
method call can also return a value that you can use.
119
Cont…
<?php
class Member
{
public $username = "";
private $loggedIn = false;
public function login() {
$this->loggedIn = true;
}
public function logout() {
$this->loggedIn = false;
}
public function isLoggedIn() {
return $this->loggedIn;
}}
120
Cont…
$member = new Member();
$member->username = "Fred";
echo $member->username . " is " . ( $member->isLoggedIn() ?
"logged in" : "logged out" ) . "<br>";
$member->login();
echo $member->username . " is " . ( $member->isLoggedIn() ?
"logged in" : "logged out" ) . "<br>";
$member->logout();
echo $member->username . " is " . ( $member->isLoggedIn() ?
"logged in" : "logged out" ) . "<br>";
?>
121
Cont…
• The above script displays the following:
Fred is logged out
Fred is logged in
Fred is logged out
122
Cont…
• Here’s how the script works:
• After defining the Member class as before, we create
a new Member object and store its value in
$member. We also set the member’s username to
“Fred”.
• We then call $member->isLoggedIn() to determine
if the member is currently logged in. isLoggedIn()
simply returns the value of the $loggedIn property.
Since $loggedIn defaults to false, isLoggedIn()
returns false to the calling code, resulting in the
message “Fred is logged out”.
123
Cont…
• Next we call the $member object’s login() method. This sets
the object’s $loggedIn property to true.
• Now, when we call isLoggedIn() again, it returns true, so our
code displays “Fred is logged in”.
• We then call the $member object’s logout() method, which
sets the $loggedIn property to false.
• Finally, we call isLoggedIn() a third time. This time it returns
false, because $loggedIn is set to false again. This causes our
code to display “Fred is logged out” once more.
124
Cont…
<?php
class Dog
{
public $hungry = 'I am hungry.';
function eat($food)
{
$this->hungry = 'not so much.';
}}
$dog = new Dog;
echo $dog->hungry."<br>"; Note: In case you’re not familiar
// Result: I am Hungry. with it, the ?: used in the example
$dog->eat('cookie'); above is the ternary operator. It’s
echo $dog->hungry; like a compact version of an if ...
//Result: not so much. else statement.
?>
125
Working with constructors
• Use a constructor whenever you want to initialize stuff when
an object is created
• This might include setting properties, opening files, and
reading data
• To create a constructor method, simply add a method with the
name __construct() to your class (that’s 2 underscores before
the word “construct”).
• PHP then automatically calls this method when an object
based on the class is created.
126
Cont…
• Here’s an example of a constructor:
class MyClass {
public function __construct() {
echo "I've just been created!";
}
}
// Displays "I've just been created!"
$myObject = new MyClass();
127
Cont…
• MyClass contains a simple constructor that displays a message
using echo.
• The last line of code in the script creates a new object based
on MyClass.
• When this happens, PHP automatically calls the constructor,
displaying the message
128
Cont…
• Here’s a somewhat more practical use of a constructor —
initializing properties:
class Member {
private $username;
private $location;
private $homepage;
public function __construct( $username, $location, $homepage )
{
$this->username = $username;
$this->location = $location;
$this->homepage = $homepage;
} 129
Cont…
public function showProfile() {
echo "<dl>";
echo "<dt>Username:</dt><dd>$this->username</dd>";
echo "<dt>Location:</dt><dd>$this->location</dd>";
echo "<dt>Homepage:</dt><dd>$this->homepage</dd>";
echo "</dl>";
}
}
$aMember = new Member( "fred", "Chicago", "http://example.com/" );
$aMember->showProfile();
130
Cont…
• When you run the above script, it displays the following:
Username:
fred
Location:
Chicago
Homepage:
http://example.com/
• Our Member class contains 3 private properties, and a
constructor that accepts 3 arguments — one for each property.
The constructor sets the object’s properties to the argument
values. The class also contains a showProfile() method that
displays the property values using echo.
131
Cont…
• The script then creates a new Member object, passing 3 values
— “fred”, “Chicago”, and “http://example.com/” — to the
constructor as it does so
• The constructor stores the values in the new object’s properties
• Finally, the script calls the object’s showProfile() method to
display the stored values
132
Cont…
• Practical Example:
<?php
//class.factorial.php
class Factorial
{
private $result = 1;
private $number;
function __construct($number)
{
$this->number = $number;
for($i=2; $i<=$number; $i++)
{
$this->result*=$i;
}
echo "__construct() executed. ";
}
133
Cont…
function factorial($number)
{
$this->number = $number;
for($i=2; $i<=$number; $i++)
{
$this->result*=$i;
}
echo "factorial() executed. ";
}
public function showResult()
{
echo "Factorial of {$this->number} is {$this->result}. ";
}}
$fact = new Factorial(5);
$fact->showResult();
//Result: __construct() executed. Factorial of 5 is 120
?>
134
Static methods, fields
• static $name = value; # declaring a static field
• # declaring a static method
public static function name(parameters) {
statements;
}
• ClassName::methodName(parameters); # calling a
• static method (outside class)
• self::methodName(parameters); # calling a static
• method (within class)
• Note:- static fields/methods are shared throughout a class
rather than replicated in every object
135
Abstract classes and interfaces
interface InterfaceName {
public function name(parameters);
public function name(parameters);
...
}
class ClassName implements InterfaceName { ...
abstract class ClassName {
abstract public function name(parameters);
...
}
136
Cont…
• Interfaces are supertypes that specify method
• headers without implementations
cannot be instantiated; cannot contain function bodies
or fields
enables polymorphism between subtypes without
sharing implementation code
• abstract classes are like interfaces, but you can
specify fields, constructors, methods
also cannot be instantiated; enables polymorphism
sharing of implementation code
137
Chapter 3
PHP with HTML forms
138
Form Validation
• User input should be validated on the browser whenever possible
(by client scripts). Browser validation is faster and reduces the
server load.
• The user will then get the error messages on the same page as
the form. This makes it easier to discover the error.
139
• Cline side form validation ? (reading assignment) =
java script
140
Server Side Validation
• PHP provides a function called IsSet(“$var”) that tests a variable to see whether it
has been assigned a value.
• And there is also empty(“$var”) function to check the value of the variable whether it
has a value or not.
Example:
From the above example we can check the variable $name value
if(!IsSet($name)){
echo”Error”;
}
OR
if(empty($name)){
echo'<script type="text/javascript">';
echo 'alert("Please fill all required information")';
echo'</script>';
}
141
PHP data processor
• The PHP $_GET and $_POST variables are used to retrieve
information from forms, like user input.
• Gather information from a website's visitor and then use PHP
to do process that information
• Are associative array variables which use form element names
as a key
PHP Form Handling
• The most important thing to notice when dealing with HTML
forms and PHP is that any form element in an HTML page
will automatically be available to your PHP script
142
Cont…
Example
The example below contains an HTML form with two
input fields and a submit button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
143
Cont…
• When a user fills out the form above and click on the submit
button, the form data is sent to a PHP file, called
"welcome.php":
• "welcome.php" looks like this:
<html>
<body>
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
Output :
Welcome John!
You are 28 years old.
144
PHP $_GET Function
• The built-in $_GET function is used to collect values in a form
with method="get".
145
Example
Cont…
<form action="welcome.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
When the user clicks the "Submit" button, the URL sent to the server could look
something like this:
http://www.w3schools.com/welcome.php?fname=Peter&age=37
The "welcome.php" file can now use the $_GET function to collect form data
(the names of the form fields will automatically be the keys in the $_GET array):
147
PHP $_POST Function
• The built-in $_POST function is used to collect
values from a form sent with method="post".
• Information sent from a form with the POST method
is invisible to others and has no limits on the amount
of information to send.
• Note: However, there is an 8 Mb max size for the
POST method, by default (can be changed by setting
the post_max_size in the php.ini file).
148
Cont…
Example
When the user clicks the "Submit" button, the URL will look like this:
http://www.w3schools.com/welcome.php
The "welcome.php" file can now use the $_POST function to collect form
data (the names of the form fields will automatically be the keys in the
$_POST array):
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.
149
The PHP $_REQUEST Function
• The PHP built-in $_REQUEST function contains the contents
of both $_GET, $_POST, and $_COOKIE
• The $_REQUEST function can be used to collect form data
sent with both the GET and POST methods
Example
150
Cont…
Order.Html Process.php
<html><body> <html><body>
<h4>Tizag Art Supply Order Form</h4>
<?php
<form action="process.php“
$quantity = $_POST['quantity'];
method="post">
<select name="item"> $item = $_POST['item'];
<option>Paint</option> echo "You ordered ". $quantity . " " .
<option>Brushes</option> $item . ".<br />";
<option>Erasers</option> echo "Thank you for ordering from
</select> Tizag Art Supplies!";
Quantity: <input name="quantity" ?>
type="text" /> </body></html>
<input type="submit" />
</form>
</body></html>
151
Assignment 2
Example: After filling the following registration form the data
will be processed in the server and display all the data back to
the user.
<form name=”reg_frm” action=”registration.php”
method=”POST”>
152
Chapter 4
153
File Vs Database
• Many applications require the long-term storage of information.
• Information can be stored on the server in flat files or in databases.
• Flat files are text files stored in the computer file system.
• You can access and edit these files by using any text editors such as
notepad or gedit.
• The information in the flat file is stored as strings, and the PHP script that
retrieves the data needs to know how the data is stored.
• For example, to retrieve a customer name from a file, the PHP script needs
to know that the customer name is stored in the first 20 characters of every
line.
• Using a database for data storage requires you to install and learn to use
database software, such as MySQL or Oracle.
• The data is stored in the database and can only be accessed by the database
software.
• Databases can store very complex information that you can retrieve easily.
154
Cont…
• You don’t need to know how the data is stored, just how to interact with
the database software.
• The database software handles the storage and delivers the data, without
the script needing to know exactly where or how the customer name is
stored.
• Flat files have some advantages over databases:
– Available and versatile: You can create and save data in any operating
system’s file system. You don’t need to install any extra software.
– Additionally, text data stored in flat files can be read by a variety of
software programs, such as word processors or spreadsheets.
– Easy to use: You don’t need to do any extra preparation, such as install
database software, design a database, create a database, and so on.
– Just create the file and store the data with statements in your PHP
script.
155
– Smaller: Flat files store data by using less disk space than databases.
Cont…
• Databases have advantages as well:
– Security: A database provides a security layer of its own, in addition to
the security provided by the operating system.
– A database protects the data from outside intrusion better than a flat
file.
– Ability to handle multiple users: When many users store or access data
in a single file, such as a file containing names and addresses, a
database ensures that users take their turn with the file to avoid 156
PHP Files
• Manipulating files is a basic necessity for serious
programmers and
157
PHP - File Create and Open
• In PHP, a file is created using a command that is also used to
open files. It may seem a little confusing, but we'll try to
clarify this conundrum.
• In PHP the fopen function is used to open files.
• However, it can also create a file if it does not find the file
specified in the function call.
• So if you use fopen on a file that does not exist, it will create
it, given that you open the file for writing or appending (more
on this later).
158
Cont…
• The fopen() function is used to open files in PHP.
• The first parameter of this function contains the name of the file to
be opened and the second parameter specifies in which mode the
file should be opened:
• <html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
159
Cont…
• The file may be opened in one of the following
modes:
Note: If the fopen() function is unable to open the specified file, it returns
0 (false).
160
Cont…
Example
The following example generates a message if the fopen() function is unable to
open the specified file:
<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body>
</html>
161
Closing a File
The fclose() function is used to close an open file:
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
162
Check End-of-file
• The feof() function checks if the "end-of-file" (EOF)
has been reached.
163
Reading a File Line by Line
• The fgets() function is used to read a single line from
a file.
• Note: After a call to this function the file pointer has
moved to the next line.
164
Cont…
Example
The example below reads a file line by line, until the
end of file is reached:
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
165
Reading a File Character by Character
• The fgetc() function is used to read a single character
from a file.
• Note: After a call to this function the file pointer
moves to the next character.
166
Cont…
Example
The example below reads a file character by character,
until the end of file is reached:
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
167
Writing to a File
• Writing to a file in PHP is relatively simple.
• You can use either of the functions fwrite() or fputs()
• fputs() is an alias to fwrite().
• We call fwrite() in the following:
fwrite($fp, $outputstring);
• This tells PHP to write the string stored in $outputstring to the file pointed to
by $fp.
• The function fwrite() actually takes three parameters but the third one is
optional.
• The prototype for fwrite() is:
int fwrite(int fp, string str, int [length]);
168
Cont…
• The third parameter, length, is the maximum number
of bytes to write.
• If this parameter is supplied, fwrite() will write string
to the file pointed to by fp until it reaches the end of
string or has written length bytes, whichever comes
first.
• Example: write data to file
<?php
$fh = fopen(“test.txt”,”a”);
$data = “This content is written to file \n”;
$data = $data . “This line is also written”;
fwrite($fh, $data);
fclose($fh);
?> 169
Getting information about files
• Often you want to know information about a file.
• PHP has functions that allow you to find out file information
about the files from within a script.
• You can find out whether a file exists with the file_exists
statement, as follows:
$result = file_exists(filename);
• After this statement, $result contains either TRUE or FALSE.
• The function is often used in a conditional statement, such as
the following:
if(!file_exists(“stuff.txt”))
{
echo “File not found!\n”;
}
170
Cont….
Function What It Does Output
is_file(“stuff.txt”) Tests whether the file is a regular file, rather than TRUE or FALSE
a directory or other special type of file
is_dir(“stuff.txt”) Tests whether the file is a directory TRUE or FALSE
is_executable(“do.txt”) Tests whether the file is executable TRUE or FALSE
is_writable(“stuff.txt”) Tests whether you can write to the file TRUE or FALSE
is_readable(“stuff.txt”) Tests whether you can read the file TRUE or FALSE
filesize(“stuff.txt”) Returns the file size in bytes Integer or FALSE
basename(“/t1/do.txt”) Returns the filename from the path do.txt
dirname(“/t1/do.txt”) Returns the directory name from the path /t1
copy(oldfile, newfile) Copy an existing file into a new file TRUE or FALSE
rename(oldname,newname) renames a file oldname to newname TRUE or FALSE
unlink(“badfile.txt”) deletes an unwanted file TRUE or FALSE
171
Cont…
• Example:
if(!file_exists(“library.txt”))
copy(“book.txt”, ”library.txt”);
else
echo “File already exists!\n”;
172
Reusing Code
173
Cont…
• One of the goals of software engineers is to reuse code instead of
writing new code.
• Reusing existing code reduces costs, increases reliability, and
improves consistency.
• Ideally, a new project is created by combining existing reusable
components, with a minimum of development from scratch.
• PHP provides two very simple, yet very useful, statements to allow
you to reuse any type of code.
• Using include or require statement, you can load a file into your PHP
script.
• The file can contain anything you would normally type in a script
including PHP statements, text, HTML tags, etc
174
PHP Include File
• You can insert the content of one PHP file into another PHP
file before the server executes it, with the include() or
require() function
• The two functions are identical in every way, except how they
handle errors:
include() generates a warning, but the script will continue
execution
require() generates a fatal error, and the script will stop
175
PHP include() Function
• The include() function takes all the content in a specified file
and includes it in the current file
• If an error occurs, the include() function generates a warning,
but the script will continue execution
Example 1
Assume that you have a standard header file, called "header.php". To include the
header file in a page, use the include() function:
<html>
<body>
<?php include("header.php"); ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
176
Cont…
Example 2
Assume we have a standard menu file, called "menu.php", that should be used on all pages:
<a href="/default.php">Home</a>
<a href="/tutorials.php">Tutorials</a>
<a href="/references.php">References</a>
<a href="/examples.php">Examples</a>
<a href="/about.php">About Us</a>
<a href="/contact.php">Contact Us</a>
177
Cont…
All pages in the Web site should include this menu file. Here is how it can be done:
<html>
<body>
<div class="leftmenu">
<?php include("menu.php"); ?>
</div>
</body>
</html>
178
PHP require() Function
• The require() function is identical to include(), except
that it handles errors differently.
• If an error occurs, the include() function generates a
warning, but the script will continue execution.
179
Cont….
Error Example include() Function
<html>
<body>
<?php
include("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
180
Cont….
181
Cont…
Error Example require() Function
Now, let's run the same example with the require() function.
<html>
<body>
<?php
require("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
182
Cont…
183
PHP File Upload
• You may want users to upload files to your Web site.
• For example, you may want users to be able to upload resumes to
your job-search Web site or pictures to your photo album Web site.
• Security can be an issue when uploading files.
• Allowing strangers to load files onto your computer is risky; malicious
files are possible.
• So, check the files for as many factors as possible after they are uploaded,
using conditional statements to check file characteristics, such as checking
for the expected file type and for the size.
• In some cases, for even more security, it may be a good idea to change the
name of the file to something else so users don’t know where their files
are or what they’re called.
184
Cont…
Create an Upload-File Form
• To allow users to upload files from a form can be very useful.
• Look at the following HTML form for uploading files:
<html>
<body>
<form action="upload_file.php" method="post“
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
185
Cont…
Notice the following about the HTML form above:
• The enctype attribute of the <form> tag specifies which
content-type to use when submitting the form.
• “multipart/form-data" is used when a form requires
binary data, like the contents of a file, to be uploaded
• The type="file" attribute of the <input> tag specifies
that the input should be processed as a file.
• For example, when viewed in a browser, there will be a
browse-button next to the input field
Note: Allowing users to upload files is a big security risk.
Only permit trusted users to perform file uploads.
186
Accessing Information About An Uploaded File
• Along with the file, information about the file is sent with the form.
• This information is stored in the PHP built-in array called $_FILES
• An array of information is available for each file that was uploaded.
• You can obtain the information from the array by using the name of
the field.
$_FILES[‘fieldname’][‘name’] – contains filename
$_FILES[‘fieldname’][‘type’] – contains type of file
$_FILES[‘fieldname’][‘tmp_name’] – contains temporary location
of file
$_FILES[‘fieldname’][‘size’] – contains size of file
• For example, suppose you use the following field to upload a file:
<input type=”file” name=”user_file”> 187
Create The Upload Script
The "upload_file.php" file contains the code for uploading a file:
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br
/>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>
188
Cont…
• By using the global PHP $_FILES array you can upload files
from a client computer to the remote server.
• The first parameter is the form's input name and the second index
can be either "name", "type", "size", "tmp_name" or "error". Like
this:
$_FILES["file"]["name"] - the name of the uploaded file
$_FILES["file"]["type"] - the type of the uploaded file
$_FILES["file"]["size"] - the size in bytes of the uploaded file
$_FILES["file"]["tmp_name"] - the name of the temporary copy of the file
stored on the server
$_FILES["file"]["error"] - the error code resulting from the file upload
• This is a very simple way of uploading files. For security reasons,
you should add restrictions on what the user is allowed to upload.
189
Restrictions on Upload
• In this script we add some restrictions to the file upload. The
user may only upload .gif or .jpeg files and the file size must
be under 20 kb:
• You can use the following statement to move the file to your
desired location, in this case, c:\data\new_file.txt:
move_uploaded_file($_FILES[‘user_file’][‘tmp_name’],
‘c:/data/new_file.txt’);
The destination directory (in this case, c:\data) must exist before the file can be
moved to it.
This statement doesn’t create the destination directory. 191
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
192
Cont…
• if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
} The script above checks if the file already exists, if it
else does not, it copies the file to the specified folder.
{ Note: This example saves the file to a new folder
echo "Invalid file"; called "upload"
}
?>
193
Chapter 5: Connecting to
Databases
194
Databases
Database is an efficiently organized collection of data
A database is an electronic file cabinet that stores information in an organized manner so
that you can find it when you need it.
Database Architecture
There are two main types
1. Embedded database
• Runs and store data on the same machine
• Can’t be shared between different machines because each one would simply end up
storing and manipulating its own separate version of the data.
• Mostly for smaller applications
195
Cont…
2. Client / server Databases
• Designed for use over networks
In principal,
Building the database is independent of the PHP programs that your application uses to
interact with the database
PHP can be connected with any of database systems but MySQL offers the following
advantages,
MySQL is a fast, easy-to-use RDBMS used on many Web sites.
It is popular database being used on the web today
Freely available to install and run on client machine
Easy to install on wide range of operating systems
MySQLs great strengths lie in speed and efficiency so It s particularly suited to web-
based applications.
197
Relational database and MySQL
198
SQL Data Types
199
Working on MySQL with PHP
200
Database Tables
• A database most often contains one or more tables.
• Each table is identified by a name (e.g. "Customers"
or "Orders"). Tables contain records (rows) with data.
• Below is an example of a table called "Persons":
• The table above contains three records (one for each person)
and four columns (LastName, FirstName, Address, and City).
201
Queries
• A query is a question or a request.
• With MySQL, we can query a database for specific
information and have a recordset returned.
• Look at the following query:
SELECT LastName FROM Persons
The query above selects all the data in the "LastName" column from
the "Persons" table, and will return a recordset like this:
202
Cont…
SELECT : retrieves data from a database
DELETE : Deletes data from a database
REPLACE : replace the same records in a table
UPDATE : changes the value of the data
CREATE : creates a database, table or index
ALTER : Modifies the structure of the table
DROP : wipes out a database or a table
And so on….
203
How PHP communicates with MySQL
204
PHP MySQL Connect to a Database
• Create a Connection to a MySQL Database
• Before you can access data in a database, you must create a
connection to the database.
• In PHP, this is done with the mysql_connect() function.
• Syntax
mysql_connect(servername,username,password);
205
Cont…
Example
In the following example we store the connection in a variable ($con) for
later use in the script. The "die" part will be executed if the connection fails:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
?>
206
Cont…
Closing a Connection
The connection will be closed automatically when the script ends.
To close the connection before, use the mysql_close() function:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
207
Create a Database
• The CREATE DATABASE statement is used to
create a database in MySQL.
• Syntax
CREATE DATABASE database_name
• To get PHP to execute the statement above we must
use the mysql_query() function. This function is
used to send a query or command to a MySQL
connection.
208
Example
Cont…
The following example creates a database called "my_db":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con);
?>
209
Create a Table
The CREATE TABLE statement is used to create a table in
MySQL.
Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
210
• Example
• The following example creates a table named "Persons", with three
columns. The column names will be "FirstName", "LastName" and "Age":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
211
Cont…
• // Create table
mysql_select_db("my_db", $con); // to make active DB
$sql = "CREATE TABLE Persons
(
FirstName varchar(15), Important: A database must be
LastName varchar(15), selected before a table can be created.
Age int The database is selected with the
)";
mysql_select_db() function
// Execute query
Note: When you create a database
mysql_query($sql,$con);
field of type varchar, you must
mysql_close($con); specify the maximum length of the
?> field, e.g. varchar(15).
212
Primary Keys and Auto Increment Fields
• Each table should have a primary key field.
• A primary key is used to uniquely identify the rows in a table. Each
primary key value must be unique within the table.
• Furthermore, the primary key field cannot be null because the database
engine requires a value to locate the record.
• The following example sets the personID field as the primary key field.
The primary key field is often an ID number, and is often used with the
AUTO_INCREMENT setting. AUTO_INCREMENT automatically
increases the value of the field by 1 each time a new record is added.
• To ensure that the primary key field cannot be null, we must add the
NOT NULL setting to the field.
213
Cont…
Example
$sql = "CREATE TABLE Persons
(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)";
mysql_query($sql,$con);
214
Insert Data Into a Database Table
215
Cont…
• The second form specifies both the column names and the
values to be inserted:
• INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
• To get PHP to execute the statements above we must use the
mysql_query() function.
216
Cont…
• Example
• In the previous section we created a table named "Persons",
with three columns; "Firstname", "Lastname" and "Age". We
will use the same table in this example. The following
example adds two new records to the "Persons" table:
217
Cont…
• <?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");
mysql_close($con);
?>
218
Insert Data From a Form Into a Database
• Now we will create an HTML form that can be used to add new records to
the "Persons" table.
• Here is the HTML form:
• <html>
<body>
</body>
</html>
219
Cont…
• When a user clicks the submit button in the HTML form in the
example above, the form data is sent to "insert.php".
• The "insert.php" file connects to a database, and retrieves the
values from the form with the PHP $_POST variables.
• Then, the mysql_query() function executes the INSERT INTO
statement, and a new record will be added to the "Persons"
table.
220
Cont…
• Here is the "insert.php" page:
• <?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
221
PHP MySQL Select
• Select Data From a Database Table
• The SELECT statement is used to select data from a database.
• Syntax
SELECT column_name(s)
FROM table_name
• To get PHP to execute the statement above we must use the
mysql_query() function.
• This function is used to send a query or command to a MySQL
connection.
222
Example
The following example selects all the data stored in the "Persons" table (The
* character selects all the data in the table):
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysql_close($con);
?>
223
Cont…
• mysql_fetch_array() function to return the first row from the
recordset as an array.
• Each call to mysql_fetch_array() returns the next row in the
recordset.
• The while loop loops through all the records in the recordset.
• To print the value of each row, we use the PHP $row variable
($row['FirstName'] and $row['LastName']).
• Output : -
224
Display the Result in an HTML Table
• <?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?> 225
Where Clause
• The WHERE clause is used to extract only those records that
fulfill a specified criterion.
• Syntax
• SELECT column_name(s)
FROM table_name
WHERE column_name operator value
• To get PHP to execute the statement above we must use the
mysql_query() function. This function is used to send a query or
command to a MySQL connection.
• Example
• The following example selects all rows from the "Persons" table
where "FirstName='Peter':
226
Cont…
• <?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
?> output : Peter Griffin
227
The ORDER BY Keyword
• The ORDER BY keyword is used to sort the data in a
recordset.
• The ORDER BY keyword sort the records in ascending order
by default.
• If you want to sort the records in a descending order, you can
use the DESC keyword.
• Syntax
• SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
228
• Example
• The following example selects all the data stored in the "Persons" table, and sorts the
result by the "Age" column:
• <?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br />";
}
mysql_close($con);
Glenn Quagmire 33
?> output : Peter Griffin 35
229
PHP MySQL Update
• The UPDATE statement is used to update existing records in a
table.
• Syntax
• UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
• Note: 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!
230
Cont…
• To get PHP to execute the statement above we must
use the mysql_query() function.
• This function is used to send a query or command to
a MySQL connection.
Example
• Earlier in the tutorial we created a table named
"Persons". Here is how it looks:
231
Cont…
• <?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_close($con);
?>
232
Cont…
• After the update, the "Persons" table will look like
this:
233
PHP MySQL Delete
• Data can be deleted from MySQL tables by executing SQL DELETE
statement through PHP function mysql_query.
• Syntax
• DELETE from table-name where condition
Example
• <?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query(“DELETE From Persons
WHERE Age = 23);
mysql_close($con);
?> 234
Chapter 6: Cookies and Sessions
235
What is session control ?
• “HTTP is stateless protocol” , means protocol has no
built-in way of maintaining state between two
transactions.
• When a user requests one page, followed by another ,
HTTP does not provide a way for you to tell that both
requests came from the same user.
• The idea of session control is to be able to track a user
during a single session on a website.
• Can able to support logging in a user and showing content
to user authorization level or personal preferences.
• To track users behavior
236
Understanding Basic Session Functionality
• Session in PHP is driven by a unique session ID, a cryptography
random number.
• This session ID is generated by PHP and stored on the client side
for lifetime of a session.
• It can be either stored on a user’s computer in a cookie or passed
along through URLs
• The session ID acts as a key that allows you to register particular
variables as so – called session variables.
• The contents of these variables are stored at the server
• The session ID is the only information visible at the client side
• By default the session variables are stored in flat files on the
server
237
What is a cookie?
• A cookie is a small piece of information that scripts can store on a
client side machine
• You can store information in cookies and then retrieve it.
• You store cookies by using the setcookie function.
• The general format is as follows:
setcookie(“variable”,”value”);
• The variable is the variable name, but you do not include the dollar
sign ($).
• This statement stores the information only until the user leaves your
Web site.
• For example, the following statement stores the pair city=Jimma in
the cookie file on the user’s computer:
setcookie(“city”,”Jimma”);
238
Cont…
• When the user moves to the next page, the cookie information
is available in the built-in array called $_COOKIE.
• The next Web page can display the information from the
cookie by using the following statement.
echo “Your home city is “.$_COOKIE[‘city’];
• The output from this statement is as follows:
Your home city is Jimma
• Setting expiration dates
• If you want the information stored in a cookie to remain in a
file on the user’s computer after the user leaves your Web site,
set your cookie with an expiration time, as follows:
setcookie(“variable”,”value”,expiretime);
239
Cont…
• The expire time value sets the time when the cookie expires.
• The value for expire time is usually set by using either the time or mktime
function as follows:
• time: This function returns the current time in a format the computer can
understand. You use the time function plus a number of seconds to set the
expiration time of the cookie:
setcookie(“state”, ”CA”, time()+3600); #expires in one hour
setcookie(“Name”, $Name, time()+(3*86400)) #expires 3 days
• mktime: This function returns a date and time in a format that the computer
can understand. You must provide the desired date and time in the
following order: hour, minute, second, month, day, and year. If any value is
not included, the current value is used.
• This is shown in the following statements:
setcookie(“state”, ”CA”, mktime(3,0,0,4,1,2003)); #expires at 3:00 AM on
April 1, 2003
setcookie(“state”, ”CA”, mktime(13,0,0,,,)); /#expires at 1:00 PM today
240
Cont…
Deleting a Cookie
• Officially, to delete a cookie, you should call setcookie() with
the name argument only:
setcookie("vegetable");
• This approach does not always work well, however, and
should not be relied on.
• It is safest to set the cookie with a date you are sure has
already expired:
setcookie("vegetable", "", time()-60);
• You should also ensure that you pass setcookie() the same
path, domain, and secure parameters as you did when
originally setting the cookie. 241
Session
Session
• A session is the time that a user spends at your Web site.
• Users may view many Web pages between the time they enter your site and
leave it.
• Often you want information to be available for a complete session.
• After you create a session, the session variables are available for your use
on any other Web page.
• To make session information available, PHP does the following:
– PHP assigns a session ID number.
– The number is a really long number that is unique for the user and that no one
could possibly guess. The session ID is stored in a PHP system variable named
PHPSESSID.
– PHP stores the variables that you want saved for the session in a file on the
server.
– The file is named with the session ID number.
– It’s stored in a directory specified by session.save_path in the php.ini file.
– PHP passes the session ID number to every page. 242
Cont…
– If the user has cookies turned on, PHP passes the session
ID by using cookies.
– If the user has cookies turned off, PHP behavior depends
on whether trans-sid is turned on in php.ini.
– PHP gets the variables from the session file for each new
session page.
– Whenever a user opens a new page that is part of the
session, PHP gets the variables from the file by using the
session ID number that was passed from the previous page.
– The variables are available in the $_SESSION array.
243
Implementing Simple Sessions
• The basic steps of using sessions are
1. Starting a session
2. Registering session variables
3. Using session variables
4. Deregistering session variables and destroying the
session
244
Starting a Session
• Before use session functionality , need to actually
begin a session
• There are ways to do this , simple method is to begin
a script with a call to the session_start() function :
session_start ();
• This function checks to see whether there is already a
current session. If not , it will essentially create one ,
providing access to the superglobal $SESSION array
245
Cont…
• If a session already exist , session_start() loads the
registered session variables so you can use them.
• It’s essential to call session_start() at the start of all
your scripts that use sessions. If this function is not
called , anything stored in the session will not be
available in this script.
246
Registering Session Variables
• Session variables have been stored in the superglobal array
$_SESSION
• To create a session variable , simply set an element in this
array as follows
$_SESSION[‘myvar’] = 5;
• The session variable you have just created will be tracked until
the session ends or until you manually unset it
247
Using session variables
• Access the session variable with the $_SESSION
super-global array
• For example :- $_SESSION[‘myvar’];
• To check whether session variables have been set
(isset() or empty()). Remember that variables can be
set by the user via GET or POST
• To check a variable to see whether it is a registered
session variable by checking in $_SESSION.
• For example
if (isset ($_SESSION[‘myvar’])) ….
248
Unsetting Variables and Destroying the
session
• When you are finished with a session variable , you
can unset it.
• Do this directly by unsetting the appropriate element
of the $_SESSION array , as in this example
unset($_SESSION[‘myvar’])
• Note that the use of session_unregister() or
session_unset() is no longer required and is not
recommended
249
Cont…
• Should not try to unset the whole $_SESSION array
because doing so will effectively disable sessions. To
unset all the session variables at once , use
• $_SESSION = array();
• When you are finished with a session , you should
first unset all the variables and then call
session_destroy(); // to clean up the session ID
250
Creating a simple Session Example
• Eg1:- page1.php starting a session and creating a
session variable
• <?php
session_start();
$_SESSION[‘sess_var’] = “Hello World”;
echo “The content of session variable is”.
$_SESSION[‘sess_var’]. “<br/>”;
?>
<a href = ‘page2.php’> Next page </a>
251
Cont…
• This script creates the variable and sets its value. The
output of this script is shown in below Figure5.1
252
Cont…
• The final value of the variable on the page is the one
that will be available on subsequent pages.
253
Cont…
• Eg2:- page2.php – Accessing a Session Variable and Unsetting It
<?php
session_start();
Echo “content of session variable is “.
$_SESSION[‘sess_var’].”<br />”;
unset($_SESSION[‘sess_var’]);
?>
<a href = “page3.php”> Next Page</a>
• After you call session_start() , the variable
$_SESSION[‘sess_var’] is variable with its previously stored
value , as you can see in Figure 5.2
254
Cont…
255
Cont…
• Finally , you pass along to page3.php , the final script
in the example. The code for this script is shown
below
Page3.php:- Ending the session
<?php
session_start();
echo “the content of session variable is”.
$_SESSION[‘sess_var’].”<br />”;
session_destroy();
?>
256
Cont…
• As you can see in Figure 5.3 , you no longer access to
the persistent value of $_SESSION[‘sess_var’]
257
Implementing Authentication with Session
Control
• Most common use of session control is to keep track of users
after they have been authenticated via a login mechanism
• In this example , you combine authentication from a MYSQL
database with use of sessions to provide this functionality.
• To under stand how this example works , look at Figure 5.4 ,
which shows the initial page displayed by authmain.php
258
Cont…
259