WT - Unit IV
WT - Unit IV
1956
Approved by AICTE, COA and BCI, New Delhi
B20CIO503
Web Technology & its Application
Design dynamic and interactive web pages by embedding Java Script code
in HTML.
OE_WT_Unit_II 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
// PHP code goes here
?>
Below, we have an example of a simple PHP file, with a PHP script that uses a
built-in PHP function "echo" to output the text "Hello World!" on a web page
OE_WT_Unit_II 8
Example :-
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1> Output
<?php
echo "Hello World!";
?>
</body>
</html>
OE_WT_Unit_II 9
Comments in PHP
A comment in PHP code is a line that is not executed as a part of
the program. Its only purpose is to be read by someone who is
looking at the code.
PHP supports several ways of commenting:
-> Syntax for single-line comments:
# This is also a single-line comment
-> Syntax for multiple-line comments:
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/ OE_WT_Unit_II 10
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;
?>
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)
PHP variable names are case-sensitive!
OE_WT_Unit_II 11
PHP Data Types
OE_WT_Unit_II 12
Decision Making Statements
OE_WT_Unit_II 13
PHP - The if Statement
The if statement executes some code if one condition is true.
if (condition)
Syntax {
code to be executed if condition is
true;
}
<!DOCTYPE html>
<html> Output
Example
<body>
Have a good day!
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
</body> OE_WT_Unit_II 14
</html>
PHP - The if...else Statement
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;
}
OE_WT_Unit_II 15
PHP - The if...else Statement
Example
<?php
$t = date("H");
OE_WT_Unit_II 16
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;
}
OE_WT_Unit_II 17
PHP - The if...elseif...else Statement
Example
<?php
$t = date("H");
OE_WT_Unit_II 18
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.
OE_WT_Unit_II 19
PHP - switch Statement
Example
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!"; Output
break;
case "green": Your favorite color is red!
echo "Your favorite color is
green!";
break;
default:
echo "Your favorite color is neither
red, blue, nor green!";
}
?>
OE_WT_Unit_II 20
PHP 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:
o while - loops through a block of code as long as the specified condition
is true
o do...while - loops through a block of code once, and then repeats the
loop as long as the specified condition is true
o for - loops through a block of code a specified number of times
o foreach - loops through a block of code for each element in an array
OE_WT_Unit_II 21
PHP - while Loop
The while loop executes a block of code as long as the specified condition is
true.. Example
Syntax <?php
$x = 1;
OE_WT_Unit_II 24
PHP for Loop
Output
OE_WT_Unit_II 25
PHP for each 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.
Output
OE_WT_Unit_II 26
Arrays in PHP
OE_WT_Unit_II 27
There are two ways to create an array
$array_name=array(value1,value2,value3,.... etc);
Or
$array[key]=value;
Example; $rollno=array(110,1102,1106,1109);
$colors=array(“Red”,”Green”,”Blue”);
Or
$rollno[0]=110; $rollno[1]=1102;
$rollno[2]=1106;
OE_WT_Unit_II 28
Associative arrays
Arrays with named keys are called associative array. They have index as
string.
This type of array is also referred to as a hash or map. An associative array
assigns names to positions in the array.
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";
OE_WT_Unit_II 29
Multidimensional Arrays
A multidimensional array is an array containing one or more arrays. The
values for an array can be any PHP object, which includes other arrays.
$forecast = array("Mon" => 40, "Tue" => 47, "Wed" => 52, "Thu" => 40,
"Fri" => 37);
Key value
echo $forecast["Tue"]; // outputs 47
echo $forecast["Thu"]; // outputs 40
40 | 47 | 52 | 40 | 37
$forecast
"Mon" | "Tue" | "Wed" | "Thu" | "Fri" Keys Values
OE_WT_Unit_II 30
Multidimensional Arrays
Array with strings as keys and integers as values
<?php $AmazonProducts = array( array(“BOOK", "Books", 50),
array("DVDs", “Movies", 15),
array(“CDs", “Music", 20)
);
for ($row = 0; $row < 3; $row++) {
for ($column = 0; $column < 3; $column++) { ?>
<p> | <?= $AmazonProducts[$row][$column] ?>
<?php } ?>
</p>
<?php } ?>
PHP
Syntax
function functionName() {
code to be executed;
}
Output
OE_WT_Unit_II 32
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:
OE_WT_Unit_II 33
PHP Forms
Forms are used to collect information and pass it to server. Form elements
are used to input and manipulate data.
PHP Global Variables - Superglobals
Several 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 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.
OE_WT_Unit_II 34
PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about
headers, paths, and script locations.
PHP $_REQUEST
PHP $_REQUEST is used to collect data after submitting an HTML form.
PHP $_POST
PHP $_POST is widely used to collect form data after submitting an HTML
form with method="post". $_POST is also widely used to pass variables.
PHP $_GET
PHP $_GET can also be used to collect form data after submitting an HTML
form with method="get".
OE_WT_Unit_II 35
Difference between GET and POST methods
GET method POST method
It remain in the browser history It does not remain in the browser history
OE_WT_Unit_II 36
When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names
and values are displayed in the URL). GET also has limits on the amount of information to send.
The limitation is about 2000 characters. However, because the variables are displayed in the
URL, it is possible to bookmark the page. This can be useful in some cases.
Note: GET should NEVER be used for sending passwords or other sensitive information!
Moreover POST supports advanced functionality such as support for multi-part binary input
while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the
page.
OE_WT_Unit_II 37
Basic File Handling in PHP
PHP allows you to work with files and directories stored on the Web server.
This is very useful, because it means your PHP scripts can store
information outside the scripts themselves.
A file is nothing more than an ordered sequence of bytes stored on a hard
disk or other storage media.
A directory is a special type of file that holds the names of the files and
directories inside the folder (sometimes denoted as subdirectories or
subfolders ) and pointers to their storage areas on the media.
Including Files include() allows you to include the code contained in
another library or script file inside a php file, just as if the code had been
copied and pasted into the php file.
OE_WT_Unit_II 38
PHP provides some functions that enable you to access useful file
information.
file_exists() to discover whether a file exists before attempting to open it:
for Ex:- file_exists( “myfile.txt” )
file_exists() returns true if the file at the specified path exists, or false
otherwise.
filesize() :- to determine the size of a file on the hard disk.
For Ex:- filesize( “myfile.txt” )
This returns the size of the specified file in bytes, or false upon error
OE_WT_Unit_II 39
Opening a File with fopen()
The fopen() function opens a file and returns a file handle associated with
the file. The first argument passed to fopen() specifies the name of the file
you want to open, and the second argument specifies the mode , or how the
file is to be used.
For example: $handle = fopen( “data.txt”, “r” ); The first argument can be
just a filename ( “ data.txt “ ), in which case PHP will look for the file in
the current directory, or it can be a relative ( ” ../data.txt “ ) or absolute
( “ /myfiles/data.txt “ ) path to a file
The second argument to fopen() tells PHP how you're going to use the file.
It can take one of the following string values:
OE_WT_Unit_II 40
Value Description
R Open the file for reading only.
The file pointer is placed at the beginning of the file
r+ Open the file for reading and writing. The file pointer is placed at the beginning
of the file.
w Open the file for writing only. Any existing content will be lost. If the file does
not exist, PHP attempts to create it.
a Open the file for appending only. Data is written to the end of an existing file. If
the file does not exist, PHP attempts to create it.
a+ Open the file for reading and appending. Data is written to the end of an existing
file. If the file does not exist, PHP attempts to create it
OE_WT_Unit_II 41
Closing a File with fclose()
fclose() :- Once you've finished working with a file, it needs to be closed. You
can do this using fclose()
For ex:- fclose( $handle );
Reading from files using fread()
fread() :- can be used to read a string of characters from a file. It takes two
arguments: a file handle and the number of characters to read.
The function reads the specified number of characters (or less if the end of the
file is reached) and returns them as a string.
For example: $handle = fopen( “data.txt”, “r” ); $data = fread( $handle, 10 );
This code reads the first ten characters from data.txt and assigns them to
$data as a string. OE_WT_Unit_II 42
Reading from files using fgetc()
fgetc():- It is used to read only one character at a time.
fgetc() takes a single argument — a file handle — and returns just one
character from the file it points to; it returns false when it reaches the end of
the file:
For ex:- $one_char = fgetc( $handle );
Testing for the End of a File
feof():- It returns true when the file pointer has reached the end of the file (or
if an error occurs) and returns false otherwise.
It takes just one argument — the file handle to test.
For ex:- close( $handle );
OE_WT_Unit_II 43
Reading One Line at a Time
To read a line of text from an open file, call the fgets() function, passing in the
file handle. The function reads from the current file pointer to the end of the
current line, and returns the read characters as a string (or false if there was a
problem, such as the end of the file being reached).
Output Writing to a file using fwrite()
fwrite() :- function to write data to a file.
It requires two arguments: a file handle and a string to write to the file.
The function writes the contents of the string to the file, returning the
number of characters written (or false if there's an error).
OE_WT_Unit_II 44
For example:
$handle = fopen( “data.txt”, “w” );
fwrite( $handle, “ABCxyz” ); Writing to a file using fwrite()
The first line opens the file data.txt for writing, which erases any existing
data in the file. (If the file doesn't exist, PHP attempts to create it.)
The second line writes the character string “ ABCxyz ” to the beginning of
the file.
As with fread() , the file pointer moves to the position after the written
string; if you repeat the second line, fwrite() appends the same six
characters again, so that the file contains the characters “ ABCxyzABCxyz
”.
OE_WT_Unit_II 45
PHP Cookies
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.
OE_WT_Unit_II 46
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).
Output
OE_WT_Unit_II 47
Modify a Cookie Value
To modify a cookie, just set (again) the cookie using the setcookie()
function:
Output
OE_WT_Unit_II 48
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration
date in the past:
Output
OE_WT_Unit_II 49
PHP Sessions
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:
Output
OE_WT_Unit_II 50
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:
Output
OE_WT_Unit_II 51
Modify a PHP Session Variable
Output
OE_WT_Unit_II 52
OOPs Concepts in PHP
PHP is an object oriented scripting language;
•Encapsulation - – this is concerned with hiding the implementation details
and only exposing the methods. This is achieved via the use of “get” and “set”
methods etc.
•Inheritance - this is concerned with the relationship between classes. The
relationship takes the form of a parent and child. This is achieved via the use
of extends keyword
•Polymorphism - this is concerned with having a single form but many
different implementation ways. This is achieved via the use of implements
keyword
OE_WT_Unit_II 53
Before we go in detail, lets define important terms related to Object Oriented
Programming.
•Class − This is a programmer-defined data type, which includes local
functions as well as local data. You can think of a class as a template for
making many instances of the same kind (or class) of object.
•Object − An individual instance of the data structure defined by a class. You
define a class once and then make many objects that belong to it. Objects are
also known as instance.
•Member Variable − These are the variables defined inside a class. This data
will be invisible to the outside of the class and can be accessed via member
functions. These variables are called attribute of the object once an object is
created. OE_WT_Unit_II 54
•Member function − These are the function defined inside a class and are
used to access object data.
•Inheritance − When a class is defined by inheriting existing function of a
parent class then it is called inheritance. Here child class will inherit all or few
member functions and variables of a parent class.
•Parent class − A class that is inherited from by another class. This is also
called a base class or super class.
•Child Class − A class that inherits from another class. This is also called a
subclass or derived class.
•Polymorphism − This is an object oriented concept where same function can
be used for different purposes. For example function name will remain same
but it take different number of arguments and can do different task.
OE_WT_Unit_II 55
•Overloading − a type of polymorphism in which some or all of operators
have different implementations depending on the types of their arguments.
Similarly functions can also be overloaded with different implementation.
•Data Abstraction − Any representation of data in which the implementation
details are hidden (abstracted).
•Encapsulation − refers to a concept where we encapsulate all the data and
member functions together to form an object.
•Constructor − refers to a special type of function which will be called
automatically whenever there is an object formation from a class.
•Destructor − refers to a special type of function which will be called
automatically whenever an object is deleted or goes out of scope.
OE_WT_Unit_II 56
•Defining PHP Classes Here is the description of each line −
The general form for defining a new •The special form class, followed by the name of
class in PHP is as follows − the class that you want to define.
<?php •A set of braces enclosing any number of
class phpClass { variable declarations and function definitions.
var $var1; •Variable declarations start with the special
var $var2 = "constant string"; form var, which is followed by a conventional $
variable name; they may also have an initial
function myfunc ($arg1, $arg2) { assignment to a constant value.
[..] •Function definitions look much like standalone
} PHP functions but are local to the class and will
[..] be used to set and access object data.
}
OE_WT_Unit_II 57
Example function getPrice(){
<?php
class Books { function setTitle($par){
var $price; }
var $title;
function getTitle(){
function setPrice($par){ }
$this->price = $par; }
} ?>
OE_WT_Unit_II 58
Creating Objects in PHP
Once a class is defined , as many objects of that class type can be created.
Following is an example of how to create object using new operator.
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
Here we have created three objects and these objects are independent of each
other and they will have their existence separately.
Calling Member Functions
After creating your objects, you will be able to call member functions related to
that object. One member function will be able to process member variable of
related object only.
OE_WT_Unit_II 59
Following example shows how to set title and prices for the three books by calling member
functions.
$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );
$physics->setPrice( 10 );
$chemistry->setPrice( 15 ); Output:-
$maths->setPrice( 7 ); This will produce the following result −
Now you call another member functions to get the values Physics for High School
set by in above example −
Advanced Chemistry
$physics->getTitle();
Algebra
$chemistry->getTitle();
$maths->getTitle(); 10
$physics->getPrice(); 15
$chemistry->getPrice(); 7
$maths->getPrice(); OE_WT_Unit_II 60
Constructors
In PHP, constructors are defined as functions (as you shall see, all methods use the function keyword) with
the name __construct(). (Note: there are two underscores _ before the word construct.)
class Artist {
// variables from previous listing still go here
...
function __construct($firstName, $lastName, $city,
$birth,
$death=null) {
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->birthCity = $city;
$this->birthDate = $birth; $picasso = new Artist("Pablo","Picasso","Malaga","Oct 25,1881", "Apr 8,1973");
$this->deathDate = $death; $dali = new Artist("Salvador","Dali","Figures","May 11 1904", "Jan 23 1989");
} OE_WT_Unit_II 61
•Methods
They define the tasks each instance of a class can perform and are useful since they associate behavior
with objects. For our artist example one could write a method to convert the artist’s details into a string
of formatted HTML. Such a method is defined in class Artist {
...
public function outputAsTable() {
$table = "<table>";
$table .= "<tr><th colspan='2'>";
$table .= $this->firstName . " " . $this->lastName;
$table .= "</th></tr>";
$table .= "<tr><td>Birth:</td>";
To output the artist, you can use the reference and method
$table .= "<td>" . $this->birthDate;
$table .= "(" . $this->birthCity . ")</td></tr>";
name as follows:
$table .= "<tr><td>Death:</td>"; $picasso = new Artist( . . . )
$table .= "<td>" . $this->deathDate . "</td></tr>";
echo $picasso->outputAsTable();
$table .= "</table>";
return $table;
}
} OE_WT_Unit_II 62
PHP and MySQL
Connecting PHP to MySQL
1)Open a connection to MySQL.
2)Specify the database to open.
3)Retrieve or insert data to/from database.
4)Close the connection.
1. Open a connection to MySQL
myysql_connect ( ) function is used to open a connection to MySQL database.
The mysql_connect( )function requires three parameters. The first is the name of the
server, the second is your username and the third your password. The function returns
True if the database worked else it returns False.
The die function is similar to exit( ) function and is used to stop execution of script if
the database cannot be connected.
mysql_select_db ( ) function is used OE_WT_Unit_II
to select a particular database. 51
2. Specify the database:- mysql_select_db ( ) function is used to select a particular
database.
3. Reading data from database
Data is read from database in two steps.
a) Execute the SQL query on database using mysql_query( ) .
b)Populate row to array using mysql_fetch_array( ).
mysql_query ( ) function :-The mysql_query( ) function is used to execute SQL query
on a database.
The function returns TRUE on success and FALSE on failure.
mysql_fetch_array( ) function
The mysql_fetch_array( ) function populate rows of a data as an array. It returns the
values from the query's result set one row at a time.
OE_WT_Unit_II 51
Creating a new table using PHP
The CREATE TABLE command can be used to create a able in PHP.
The Syntax is $SQL=”CREATE TABLE Table_Name(Column1 datatype,Column2
datatype ...)”; $select_query=mysql_query($SQL);
Inserting data into a table using PHP
The INSERT TABLE command can be used to insert data into a table. The Syntax is
$SQL=”INSERT TABLE Table_Name VALUES(“.Value1”,”.value2”,....)”;
$select_query=mysql_query($SQL);
Update data in a table using PHP
The UPDATE command can be used to update data in a table.
The Syntax is:- $SQL=”UPDATE Table_Name SET Column1=value WHERE condition”;
$select_query=mysql_query($SQL);
OE_WT_Unit_II 51
4)Close the connection.
The mysql_close ( ) function is used to close a connection to the database server.
For example, the following code closes the connection established by the $link variable:
mysql_close($link);
OE_WT_Unit_II 51
Open a Connection to MySQL
Before we can access data in the MySQL database, we need to be able to connect to the
server:
<?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";
OE_WT_Unit_II 51
?>
Close the Connection
The connection will be closed automatically when the script ends. To close the connection
before, use the following::
$conn = null;
OE_WT_Unit_II 51
The following PDO example create a database named "myDBPDO":
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
OE_WT_Unit_II 70
The data type specifies what type of data the column can hold.
•NOT NULL - Each row must contain a value for that column, null values are
not allowed
•DEFAULT value - Set a default value that is added when no other value is
passed
•UNSIGNED - Used for number types, limits the stored data to positive
numbers and zero
•AUTO INCREMENT - MySQL automatically increases the value of the field by
1 each time a new record is added
•PRIMARY KEY - Used to uniquely identify the rows in a table. The column
with PRIMARY KEY setting is often an ID number, and is often used with
AUTO_INCREMENT
OE_WT_Unit_II 71
PHP MySQL Insert Data
After a database and a table have been created, we can start adding data in
them.
In the previous topic 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.
OE_WT_Unit_II 72
PHP MySQL Insert Data
After a database and a table have been created, we can start adding data in
them.
The INSERT INTO statement is used to add new records to a MySQL table:
In the previous topic 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.
OE_WT_Unit_II 73
PHP MySQL Select Data
Select Data From a MySQL Database
The SELECT statement is used to select data from one or more tables:
OE_WT_Unit_II 74
OE_WT_Unit_II 75
PHP MySQL Use The ORDER BY
Clause
Select and Order Data From a MySQL Database
The ORDER BY clause is used to sort the result-set in ascending or
descending order.
The ORDER BY clause sorts the records in ascending order by default. To sort
the records in descending order, use the DESC keyword.
OE_WT_Unit_II 76
PHP MySQL Delete Data
The DELETE statement is used to delete records from a table:
OE_WT_Unit_II 77
THANK YOU
OE_WT_Unit_II 78