SlideShare a Scribd company logo
1 of 131
Web Systems and Technologies
Server Side Programming with PHP
1
Introduction to PHP
2
•PHP and MySQL are tricky to teach without access to a
server and a database. We'll do the best we can in the
slides that follow.
•They are also tricky considering how complex they are.
Take a look at the PHP cheat sheet I found online...
3
PHP Introduction
•PHP is a recursive acronym for “PHP: Hypertext
Preprocessor” -- It is a widely-used open source
general-purpose scripting language that is especially
suited for web development and can be embedded
into HTML.
4
PHP History
• 1994: Created by Rasmis Lesdorf, software engineer
(part of Apache Team)
• 1995: Called Personal Home Page Tool, then released as
version 2 with name PHP/FI (Form Interpreter, to
analyze SQL queries)
• Half 1997: used by 50,000 web sites
• October 1998: used by 100,000 websites
• End 1999: used by 1,000,000 websites
5
Alternatives to PHP
• Practical extraction and Report Language (Perl)
• Active Server Pages (ASP)
• Java server pages (JSP)
• Ruby
6
(Good) Topics about PHP
• Open-source
• Easy to use ( C-like and Perl-like syntax)
• Stable and fast
• Multiplatform
• Many databases support
• Many common built-in libraries
• Pre-installed in Linux distributions
7
PHP Introduction
•> PHP is a server-side scripting language
•> PHP scripts are executed on the server
•> PHP supports many databases (MySQL, Informix,
Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
•> PHP is open source software
•> PHP is free to download and use
8
PHP Introduction
•> PHP runs on different platforms (Windows, Linux,
Unix, etc.)
•> PHP is compatible with almost all servers used today
(Apache, IIS, etc.)
•> PHP is FREE to download from the official PHP
resource: www.php.net
•> PHP is easy to learn and runs efficiently on the server
side
9
PHP Introduction
•Some info on MySQL
•> MySQL is a database server
•> MySQL is ideal for both small and large applications
•> MySQL supports standard SQL
•> MySQL compiles on a number of platforms
•> MySQL is free to download and use
10
PHP Introduction
•Instead of lots of commands to output HTML (as seen
in C or Perl), PHP pages contain HTML with embedded
code that does "something" (like in the next slide, it
outputs "Hi, I'm a PHP script!").
•The PHP code is enclosed in special start and end
processing instructions <?php and ?> that allow you to
jump into and out of "PHP mode."
11
PHP Introduction
12
PHP Introduction
•PHP code is executed on the server, generating HTML
which is then sent to the client. The client would
receive the results of running that script, but would not
know what the underlying code was.
•A visual, if you please...
13
PHP Introduction
14
How PHP generates
HTML/JS Web pages
1: Client from browser send HTTP request (with POST/GET
variables)
2: Apache recognizes that a PHP script is requested and sends
the request to PHP module
3: PHP interpreter executes PHP script, collects script output
and sends it back
4: Apache replies to client using the PHP script output as HTML
output
2
Client
Browser
1 PHP
module
3
4
Apache
15
Hello World! (web oriented)
•<html>
•<head>
• <title>My personal Hello World! PHP script</title>
•</head>
•<body>
•<?
•echo “Hello World!”;
•?>
•</html>
PHP tag, allow to insert PHP
code. Interpretation by PHP
module will substitute the
code with code output
16
PHP Getting Started
•On windows, you can download and install WAMP.
With one installation and you get an Apache webserver,
database server and php.
•http://www.wampserver.com
•On mac, you can download and install MAMP.
•http://www.mamp.info/en/index.html
17
PHP Hello World
•Above is the PHP source code.
18
PHP Hello World
•It renders as HTML that looks like this:
19
PHP Hello World
•This program is extremely simple and you really did
not need to use PHP to create a page like this. All it
does is display: Hello World using the PHP echo()
statement.
•Think of this as a normal HTML file which happens to
have a set of special tags available to you that do a lot
of interesting things.
20
PHP Comments
•In PHP, we use // to make
a single-line comment or /*
and */ to make a large
comment block.
21
PHP Variables
•> Variables are used for storing values, like text strings,
numbers or arrays.
•> When a variable is declared, it can be used over and
over again in your script.
•> All variables in PHP start with a $ sign symbol.
•> The correct way of declaring a variable in PHP:
22
PHP Variables
•> In PHP, a variable does not need to be declared
before adding a value to it.
•> In the example above, you see that you do not have
to tell PHP which data type the variable is.
•> PHP automatically converts the variable to the
correct data type, depending on its value.
23
PHP Variables
•> A variable name must start with a letter or an
underscore "_" -- not a number
•> A variable name can only contain alpha-numeric
characters, underscores (a-z, A-Z, 0-9, and _ )
•> A variable name should not contain spaces. If a
variable name is more than one word, it should be
separated with an underscore ($my_string) or with
capitalization ($myString)
24
PHP Concatenation
•> The concatenation operator (.) is used to put two
string values together.
•> To concatenate two string variables together, use the
concatenation operator:
25
PHP Concatenation
•The output of the code on the last slide will be:
•If we look at the code you see that we used the
concatenation operator two times. This is because we
had to insert a third string (a space character), to
separate the two strings.
26
PHP Operators
•Operators are used to operate on values. There are
four classifications of operators:
• > Arithmetic
• > Assignment
• > Comparison
• > Logical
27
PHP Operators
28
PHP Operators
29
PHP Operators
30
PHP Operators
31
PHP Conditional Statements
•> Very often when you write code, you want to
perform different actions for different decisions.
•> You can use conditional statements in your code to
do this.
•> In PHP we have the following conditional
statements...
32
PHP Conditional Statements
•> if statement - use this statement to execute some
code only if a specified condition is true
•> if...else statement - use this statement to execute
some code if a condition is true and another code if the
condition is false
•> if...elseif....else statement - use this statement to
select one of several blocks of code to be executed
•> switch statement - use this statement to select one
of many blocks of code to be executed
33
PHP Conditional Statements
•The following example will output "Have a nice
weekend!" if the current day is Friday:
34
PHP Conditional Statements
•Use the if....else statement to execute some code if a
condition is true and another code if a condition is
false.
35
PHP Conditional Statements
•If more than one line
should be executed if a
condition is true/false, the
lines should be enclosed
within curly braces { }
36
PHP Conditional Statements
•The following example
will output "Have a nice
weekend!" if the current
day is Friday, and "Have a
nice Sunday!" if the
current day is Sunday.
Otherwise it will output
"Have a nice day!":
37
PHP Conditional Statements
•Use the switch statement to select one of many blocks
of code to be executed.
38
PHP Conditional Statements
•For switches, 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.
39
PHP Conditional Statements
40
PHP Arrays
•> An array variable is a storage area holding a number
or text. The problem is, a variable will hold only one
value.
•> An array is a special variable, which can store
multiple values in one single variable.
41
PHP Arrays
•If you have a list of items (a list of car names, for
example), storing the cars in single variables could look
like this:
42
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 best solution here is to use an array.
•> An array can hold all your variable values under a
single name. And you can access the values by referring
to the array name.
•> Each element in the array has its own index so that it
can be easily accessed.
43
PHP Arrays
• In PHP, there are three kind of arrays:
• > Numeric array - An array with a numeric index
• > Associative array - An array where each ID key is
associated with a value
• > Multidimensional array - An array containing one or
more arrays
44
PHP Numeric Arrays
•> A numeric array stores each array element with a
numeric index.
•> There are two methods to create a numeric array.
45
PHP Numeric Arrays
•In the following example the index is automatically
assigned (the index starts at 0):
•In the following example we assign the index
manually:
46
PHP Numeric Arrays
•In the following example you access the variable
values by referring to the array name and index:
•The code above will output:
47
PHP Associative Arrays
•> With an associative array, each ID key is associated
with a value.
•> When storing data about specific named values, a
numerical array is not always the best way to do it.
•> With associative arrays we can use the values as keys
and assign values to them.
48
PHP Associative Arrays
•In this example we use an array to assign ages to the
different persons:
•This example is the same as the one above, but shows
a different way of creating the array:
49
PHP Associative Arrays
50
PHP Multidimensional Arrays
•In a multidimensional array, each element in the main
array can also be an array.
•And each element in the sub-array can be an array,
and so on.
51
PHP Multidimensional Arrays
52
PHP Multidimensional Arrays
53
PHP Multidimensional Arrays
54
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 lines in a script
we can use loops to perform a task like this.
•> In PHP, we have the following looping statements:
55
PHP Loops
•> while - loops through a block of code while a
specified condition is true
•> do...while - loops through a block of code once, and
then repeats the loop as long as a 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
56
PHP Loops - While
•The while loop executes a block of code while a condition
is true. The example below defines a loop that starts with
•i=1. The loop will
•continue to run as
•long as i is less
•than, or equal to 5.
•i will increase by 1
•each time the loop
•runs:
57
PHP Loops - While
58
PHP Loops – Do ... While
•The do...while statement will always execute the block
of code once, it will then check the condition, and
repeat the loop while the condition is true.
•The next example defines a loop that starts with i=1. It
will then increment i with 1, and write some output.
Then the condition is checked, and the loop will
continue to run as long as i is less than, or equal to 5:
59
PHP Loops – Do ... While
60
PHP Loops – Do ... While
61
PHP Loops - For
62
PHP Loops - For
• Parameters:
• > init: Mostly used to set a counter (but can be any
code to be executed once at the beginning of the
loop)
• > condition: Evaluated for each loop iteration. If it
evaluates to TRUE, the loop continues. If it evaluates
to FALSE, the loop ends.
• > increment: Mostly used to increment a counter (but
can be any code to be executed at the end of the
loop)
63
PHP Loops - For
•The example below defines a loop that starts with i=1.
The loop will continue to run as long as i is less than, or
equal to 5. i will increase by 1 each time the loop runs:
64
PHP Loops - For
65
PHP Loops - Foreach
•For every loop iteration, the value of the current array
element is assigned to $value (and the array pointer is
moved by one) - so on the next loop iteration, you'll be
looking at the next array value.
66
PHP Loops - Foreach
•The following example demonstrates a loop that will
print the values of the given array:
67
PHP Loops - Foreach
68
PHP Functions
•> We will now explore how to create your own
functions.
•> To keep the script from being executed when the
page loads, you can put it into a function.
•> A function will be executed by a call to the function.
•> You may call a function from anywhere within a
page.
69
PHP Functions
•A function will be executed by a call to the function.
•> Give the function a name that reflects what the
function does
•> The function name can start with a letter or
underscore (not a number)
70
PHP Functions
•A simple function that writes a name when it is called:
71
PHP Functions - Parameters
• Adding parameters...
• > To add more functionality to a function, we can add
parameters. A parameter is just like a variable.
• > Parameters are specified after the function name,
inside the parentheses.
72
PHP Functions - Parameters
73
PHP Functions - Parameters
74
PHP Functions - Parameters
This example adds
different punctuation.
75
PHP Functions - Parameters
76
PHP Forms - $_GET Function
•> The built-in $_GET function is used to collect values
from a form sent with method="get".
•> Information sent from a form with the GET method
is visible to everyone (it will be displayed in the
browser's address bar) and has limits on the amount of
information to send (max. 100 characters).
77
PHP Forms - $_GET Function
Notice how the URL carries the information after the file name.
78
PHP Forms - $_GET Function
•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)
79
PHP Forms - $_GET Function
•> When using method="get" in HTML forms, all
variable names and values are displayed in the URL.
•> This method should not be used when sending
passwords or other sensitive information!
•> However, because the variables are displayed in the
URL, it is possible to bookmark the page. This can be
useful in some cases.
•> The get method is not suitable for large variable
values; the value cannot exceed 100 chars.
80
PHP Forms - $_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).
81
PHP Forms - $_POST Function
And here is what the code of action.php might look like:
82
PHP Forms - $_POST Function
•Apart from htmlspecialchars() and (int), it should be
obvious what this does. htmlspecialchars() makes sure
any characters that are special in html are properly
encoded so people can't inject HTML tags or Javascript
into your page.
•For the age field, since we know it is a number, we can
just convert it to an integer which will automatically get
rid of any stray characters. The $_POST['name'] and
$_POST['age'] variables are automatically set for you
by PHP.
83
PHP Forms - $_POST Function
• When to use 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.
• > However, because the variables are not displayed in
the URL, it is not possible to bookmark the page.
84
Introduction to Database & MySQL
• Using MySQL from PHP
85
Database
•A structured collection of
data
•Contains 1 or more Tables
db1
db1.table_1
db1.table_2
db1.table_3
db1.table_4
86
Table
•Tables contain records
•Records contain fields
•Fields have values
87
Creating a Database
Syntax:
CREATE DATABASE dbname;
Example:
CREATE DATABASE training;
88
Using a Database
Syntax:
USE dbname;
Example:
USE training;
89
Creating a Table
Syntax:
CREATE TABLE table_name (
field1_name field_spec,
field2_name field_spec
);
Example:
CREATE TABLE student (
st_id bigint primary key auto_increment,
st_fname varchar(100),
st_age tinyint unsigned
);
90
Querying a Table
Syntax:
SELECT <field_list> FROM <table_name>
[ WHERE <condition> ];
Example:
SELECT * FROM student;
SELECT * FROM student WHERE st_age > 20;
91
Inserting a Record
Syntax:
INSERT INTO `table_name` (<fieldlist>) VALUES
(<valuelist>};
Example:
INSERT INTO student (st_fname, st_age) VALUES
( ‘Ahmad Albab’, 20 );
92
Updating a Record
Syntax:
UPDATE table_name SET <field value list>
[ WHERE <condition> ];
Example:
UPDATE student
SET
st_fname = ‘Jat’,
st_age = 22
WHERE st_id = 1;
93
Deleting a Record or Records
Syntax:
DELETE FROM table_name [ WHERE <condition> ];
Example:
DELETE FROM student WHERE st_id = 2;
DELETE FROM student WHERE st_age < 18;
94
PHP Functions for MySQL
PHP Function Description
mysql_connect() Connect to a MySQL database server
mysql_select_db() Make a database active
mysql_query() Execute SQL statement on active database
mysql_fetch_array()
Fetch a row from query result and return as
data as an array of fields and values
mysql_insert_id()
Returns the last inserted ID from an
auto_increment field
mysql_error() Returns the last MySQL error message.
95
mysql_connect()
Syntax:
resource mysql_connect (
[string server
[, string username
[, string password
[, bool new_link
[, int client_flags]]]]]);
Example:
$dbh = mysql_connect( ‘localhost’, ‘root’, ‘’ );
96
mysql_connect()
• mysql_connect()
• The mysql_connect()function opens a non-persistent MySQL
connection.
• This function returns the connection on success, or FALSE and an
error on failure. You can hide the error output by adding an '@' in
front of the function name.
• Syntax
• mysql_connect(server,user,pwd,newlink,clientfla
g)
97
mysql_connect()
Parameter Description
server Specifies the server to connect to
user Specifies the username to log in with.
pwd Specifies the password to log in with.
newlink If a second call is made to mysql_connect() with the same arguments,
no new connection will be established; instead, the identifier of the
already opened connection will be returned
clientflag •MYSQL_CLIENT_SSL - Use SSL encryption
•MYSQL_CLIENT_COMPRESS - Use compression protocol
•MYSQL_CLIENT_IGNORE_SPACE - Allow space after function names
•MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout seconds of
inactivity before closing the connection
98
MySQL Connectivity
• Example:
• <?php
$con =
mysql_connect("localhost","mysql_user","mysq
l_pwd");
if (!$con){
die('Could not connect: ‘.mysql_error());
}
echo 'Connected successfully';
mysql_close($con);
• ?>
99
MySQL Connectivity
• mysql_close()
• The mysql_close() function closes a non-persistent MySQL
connection.
• This function returns TRUE on success, or FALSE on failure.
• Syntax:
• mysql_close(connection)
Parameter Description
connection Specifies the MySQL connection to close. If not
specified, the last connection opened by
mysql_connect() is used.
100
Try out following example to open and close a database connection
• <?php
• $dbhost = 'localhost:3036';
• $dbuser = 'guest';
• $dbpass = 'guest123';
• $conn = mysql_connect($dbhost, $dbuser,
$dbpass);
• if(! $conn ) {
• die('Could not connect: ' .
mysql_error()); }
• echo 'Connected successfully';
• mysql_close($conn);?>
101
mysql_select_db()
Syntax:
bool mysql_select_db (
string database_name
[, resource link_identifier] )
Example:
$stat = mysql_select_db( ‘training’, $dbh );
102
mysql_select_db()
• mysql_select_db()
• The mysql_select_db() function sets the active MySQL database.
• This function returns TRUE on success, or FALSE on failure.
• Syntax:
• mysql_select_db(database,connection)
Parameter Description
database Required. Specifies the database to select.
connection Optional. Specifies the MySQL connection. If not
specified, the last connection opened by
mysql_connect() or mysql_pconnect() is used.
103
mysql_select_db()
• <?php
$con = mysql_connect("localhost", “root",
“admin");
if (!$con){
die('Could not connect: '. mysql_error());
}
$db_selected = mysql_select_db("test_db",
$con);
if (!$db_selected){
die ("Can't use test_db : “.
mysql_error());
}
mysql_close($con);
• ?>
104
Example showing you how to select a database
• <?php
• $dbhost = 'localhost:3036';
• $dbuser = 'guest';
• $dbpass = 'guest123';
• $conn = mysql_connect($dbhost, $dbuser, $dbpass);
• if(! $conn ) {
• die('Could not connect: ' . mysql_error());
• }
• echo 'Connected successfully';
• mysql_select_db( 'test_db' );
• mysql_close($conn);
• ?>
105
mysql_query()
Syntax:
resource mysql_query (
string query
[, resource link_identifier] )
Example:
$rh = mysql_query( ‘SELECT * FROM student’, $dbh );
106
mysql_query()
• mysql_query()
• The mysql_query() function executes a query on a MySQL
database.
• This function returns the query handle for SELECT queries,
TRUE/FALSE for other queries, or FALSE on failure.
• Syntax
• mysql_query(query,connection)
Parameter Description
query Required. Specifies the SQL query to send (should not
end with a semicolon)
connection Optional. Specifies the MySQL connection. If not
specified, the last connection opened by
mysql_connect() or mysql_pconnect() is used. 107
Try out following example to create a database
• <?php
• $dbhost = 'localhost:3036';
• $dbuser = 'root';
• $dbpass = 'rootpassword';
• $conn = mysql_connect($dbhost, $dbuser, $dbpass);
•
• if(! $conn ) {
• die('Could not connect: ' . mysql_error());
• }
• echo 'Connected successfully';
•
108
Create a database Cont,,,,,,
• $sql = 'CREATE Database test_db';
• $retval = mysql_query( $sql, $conn );
• if(! $retval ) {
• die('Could not create database: ' . mysql_error());
• }
• echo "Database test_db created successfullyn";
• mysql_close($conn);
• ?>
109
MySQL Connectivity
• <?php
$con =
mysql_connect("localhost",”root",”admin");
if (!$con){
die('Could not connect: ' . mysql_error());
}
$sql = "CREATE DATABASE my_db";
if (mysql_query($sql,$con)){
echo "Database my_db created";
}
else{
echo "Error creating database:" .
mysql_error();
}
• ?>
110
MySQL Connectivity
• <?php
$con = mysql_connect("localhost", “root",
“admin");
if (!$con){
die('Could not connect: '. mysql_error());
}
$db_selected = mysql_select_db("test_db", $con);
if (!$db_selected){
die ("Can't use test_db : “. mysql_error());
}
• $sql="SELECT * FROM Person where
name=‘$uname’";
mysql_query($sql,$con);
mysql_close($con);
• ?>
111
mysql_fetch_array()
Syntax:
array mysql_fetch_array (
resource result
[, int result_type] )
Example:
$row = mysql_fetch_array( $rh );
112
•mysql_fetch_array()
• mysql_fetch_array()
• The mysql_fetch_array() function returns a row from
a recordset as an associative array and/or a numeric array.
• This function gets a row from the mysql_query()
function and returns an array on success, or FALSE on failure
or when there are no more rows.
• Syntax
• mysql_fetch_array(data,array_type)
113
mysql_fetch_array()
Parameter Description
data Required. Specifies which data pointer to use. The data
pointer is the result from the mysql_query() function
array_type Optional. Specifies what kind of array to return.Possible
values:
•MYSQL_ASSOC - Associative array
•MYSQL_NUM - Numeric array
•MYSQL_BOTH - Default. Both associative and numeric
array
114
mysql_fetch_row()
• mysql_fetch_row()
• The mysql_fetch_row() function returns a row from
a recordset as a numeric array.
• This function gets a row from the mysql_query()
function and returns an array on success, or FALSE on
failure or when there are no more rows.
• Syntax
• mysql_fetch_row(data)
Parameter Description
data Required. Specifies which data pointer to use. The data
pointer is the result from the mysql_query() function
115
mysql_fetch_row()
• <?php
• echo "<table>";
• while ($row = mysql_fetch_row($result))
{
• echo "<tr><td>".$row[0]
."</td><td>".$row[1].
• "</td><td>".$row[2]."</td><td>".
• $row[3]."</td></tr>";
• }
• echo "</table>";
• ?>
116
mysql_fetch_array()
• <?php
• echo "<table>";
• while ($row = mysql_fetch_array($result))
{
• echo "<tr><td>{$row[‘ID’]}
</td><td>{$row[1]}
• </td><td>{$row[2]}</td><td>
•
${row[‘mailid’]}</td></tr>";
• }
• echo "</table>";
• ?>
117
mysql_insert_id()
Syntax:
int mysql_insert_id(
[resource link_identifier] )
Example:
$newId = mysql_insert_id( $dbh );
118
mysql_error()
Syntax:
string mysql_error( [resource link_identifier] )
Example:
$errMsg = mysql_error( $dbh );
119
Include Files
• include “header.php”;
• include (“footer.php”);
• This inserts files; the code in files will be inserted into current code.
• require is identical to include except upon failure it will
also produce a fatal E_COMPILE_ERROR level error.
• In other words, it will halt the script whereas include only
emits a warning (E_WARNING) which allows the script to
continue.
120
Include Files
• The include_once statement includes and evaluates the
specified file during the execution of the script.
• This is a behavior similar to the include statement, with the only
difference being that if the code from a file has already been
included, it will not be included again.
• The require_once statement is identical to require except
PHP will check if the file has already been included, and if so, not
include (require) it again
121
PHP - Forms
<?php
if ($_POST["submit"])
echo "<h2>You clicked Submit!</h2>";
else if ($_POST["cancel"])
echo "<h2>You clicked Cancel!</h2>";
?>
<form action="form.php" method="post">
<input type="submit" name="submit"
value="Submit">
<input type="submit" name="cancel"
value="Cancel">
</form>
122
PHP - Forms
<?php
…
$term=$_REQUEST[“sterm”];
…
?>
<form action="form.php" method="post">
<input type=“text" name=“sterm"
value=“<?= $term ?>">
</form>
123
Cookies
• The setcookie() function is used to create cookies. Should be called before
<html> tag.
• setcookie(name, [value], [expire], [path], [domain],
[secure]);
• <?php setcookie("uname", $name, time()+36000); ?>
• This sets a cookie named "uname" - that expires after ten hours.
• Either a blank value or a time in the past makes the cookie expired.
124
Cookies
• To access a cookie, refer to the cookie name as a variable or use
$_COOKIE array. The isset() checks whether the cookie is set
or not
<html> <body>
<?php
if (isset($uname))// isset($_Cookie[$uname])
echo "Welcome " . $_Cookie[$uname].
"!<br />";
else
echo "You are not logged in!<br />"; ?>
?>
</body> </html>
125
Cookies
•Benefit of Cookies
• Cookies are used for authenticating, tracking, and maintaining specific
information about users
• Personalised home pages
• Electronic shopping carts.
126
Why use sessions
• A normal HTML website will not pass data from one
page to another
• All information is forgotten when a new page is
loaded
• Many websites need to pass user data from one page
to another
• for tasks like a shopping cart, which requires data(the user's
selected product) to be remembered from one page to the next
• Using PHP sessions is one solution.
127
Sessions
• The session_start() function is used to create a session.
Should be called before
• <html> tag.
<?php
session_start();
?>
128
Sessions
• <?php
• session_start();
• if (!isset($_SESSION['count']))
• $_SESSION['count'] = 0;
• else
• $_SESSION['count']++;
• ?>
129
Sessions
• session_unregister(´varname´); unregisters a session
variable
• session_destroy() destroys a session
130
mysql_connect() & Mysqli_connect
• MySQLi provides a object-oriented way for accessing MySQL
databases.
• if you use mysql_query(),
• you should use mysql_connect() to connect to your server.
• Mysqli_connect is the newer version of mysql library
131

More Related Content

Similar to PHP Server Side Programming Introduction

Similar to PHP Server Side Programming Introduction (20)

Php i-slides
Php i-slidesPhp i-slides
Php i-slides
 
Php i-slides
Php i-slidesPhp i-slides
Php i-slides
 
Php i-slides
Php i-slidesPhp i-slides
Php i-slides
 
Php i-slides (2) (1)
Php i-slides (2) (1)Php i-slides (2) (1)
Php i-slides (2) (1)
 
PHP MySQL Workshop - facehook
PHP MySQL Workshop - facehookPHP MySQL Workshop - facehook
PHP MySQL Workshop - facehook
 
php41.ppt
php41.pptphp41.ppt
php41.ppt
 
PHP InterLevel.ppt
PHP InterLevel.pptPHP InterLevel.ppt
PHP InterLevel.ppt
 
php-I-slides.ppt
php-I-slides.pptphp-I-slides.ppt
php-I-slides.ppt
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
 
Materi Dasar PHP
Materi Dasar PHPMateri Dasar PHP
Materi Dasar PHP
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php web development
Php web developmentPhp web development
Php web development
 
Web Application Development using PHP Chapter 1
Web Application Development using PHP Chapter 1Web Application Development using PHP Chapter 1
Web Application Development using PHP Chapter 1
 
php Chapter 1.pptx
php Chapter 1.pptxphp Chapter 1.pptx
php Chapter 1.pptx
 
Php intro
Php introPhp intro
Php intro
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
php
phpphp
php
 
web Based Application Devlopment using PHP
web Based Application Devlopment using PHPweb Based Application Devlopment using PHP
web Based Application Devlopment using PHP
 
php basic part one
php basic part onephp basic part one
php basic part one
 

Recently uploaded

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 

Recently uploaded (20)

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 

PHP Server Side Programming Introduction

  • 1. Web Systems and Technologies Server Side Programming with PHP 1
  • 3. •PHP and MySQL are tricky to teach without access to a server and a database. We'll do the best we can in the slides that follow. •They are also tricky considering how complex they are. Take a look at the PHP cheat sheet I found online... 3
  • 4. PHP Introduction •PHP is a recursive acronym for “PHP: Hypertext Preprocessor” -- It is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. 4
  • 5. PHP History • 1994: Created by Rasmis Lesdorf, software engineer (part of Apache Team) • 1995: Called Personal Home Page Tool, then released as version 2 with name PHP/FI (Form Interpreter, to analyze SQL queries) • Half 1997: used by 50,000 web sites • October 1998: used by 100,000 websites • End 1999: used by 1,000,000 websites 5
  • 6. Alternatives to PHP • Practical extraction and Report Language (Perl) • Active Server Pages (ASP) • Java server pages (JSP) • Ruby 6
  • 7. (Good) Topics about PHP • Open-source • Easy to use ( C-like and Perl-like syntax) • Stable and fast • Multiplatform • Many databases support • Many common built-in libraries • Pre-installed in Linux distributions 7
  • 8. PHP Introduction •> PHP is a server-side scripting language •> PHP scripts are executed on the server •> PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) •> PHP is open source software •> PHP is free to download and use 8
  • 9. PHP Introduction •> PHP runs on different platforms (Windows, Linux, Unix, etc.) •> PHP is compatible with almost all servers used today (Apache, IIS, etc.) •> PHP is FREE to download from the official PHP resource: www.php.net •> PHP is easy to learn and runs efficiently on the server side 9
  • 10. PHP Introduction •Some info on MySQL •> MySQL is a database server •> MySQL is ideal for both small and large applications •> MySQL supports standard SQL •> MySQL compiles on a number of platforms •> MySQL is free to download and use 10
  • 11. PHP Introduction •Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does "something" (like in the next slide, it outputs "Hi, I'm a PHP script!"). •The PHP code is enclosed in special start and end processing instructions <?php and ?> that allow you to jump into and out of "PHP mode." 11
  • 13. PHP Introduction •PHP code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. •A visual, if you please... 13
  • 15. How PHP generates HTML/JS Web pages 1: Client from browser send HTTP request (with POST/GET variables) 2: Apache recognizes that a PHP script is requested and sends the request to PHP module 3: PHP interpreter executes PHP script, collects script output and sends it back 4: Apache replies to client using the PHP script output as HTML output 2 Client Browser 1 PHP module 3 4 Apache 15
  • 16. Hello World! (web oriented) •<html> •<head> • <title>My personal Hello World! PHP script</title> •</head> •<body> •<? •echo “Hello World!”; •?> •</html> PHP tag, allow to insert PHP code. Interpretation by PHP module will substitute the code with code output 16
  • 17. PHP Getting Started •On windows, you can download and install WAMP. With one installation and you get an Apache webserver, database server and php. •http://www.wampserver.com •On mac, you can download and install MAMP. •http://www.mamp.info/en/index.html 17
  • 18. PHP Hello World •Above is the PHP source code. 18
  • 19. PHP Hello World •It renders as HTML that looks like this: 19
  • 20. PHP Hello World •This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo() statement. •Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things. 20
  • 21. PHP Comments •In PHP, we use // to make a single-line comment or /* and */ to make a large comment block. 21
  • 22. PHP Variables •> Variables are used for storing values, like text strings, numbers or arrays. •> When a variable is declared, it can be used over and over again in your script. •> All variables in PHP start with a $ sign symbol. •> The correct way of declaring a variable in PHP: 22
  • 23. PHP Variables •> In PHP, a variable does not need to be declared before adding a value to it. •> In the example above, you see that you do not have to tell PHP which data type the variable is. •> PHP automatically converts the variable to the correct data type, depending on its value. 23
  • 24. PHP Variables •> A variable name must start with a letter or an underscore "_" -- not a number •> A variable name can only contain alpha-numeric characters, underscores (a-z, A-Z, 0-9, and _ ) •> A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string) or with capitalization ($myString) 24
  • 25. PHP Concatenation •> The concatenation operator (.) is used to put two string values together. •> To concatenate two string variables together, use the concatenation operator: 25
  • 26. PHP Concatenation •The output of the code on the last slide will be: •If we look at the code you see that we used the concatenation operator two times. This is because we had to insert a third string (a space character), to separate the two strings. 26
  • 27. PHP Operators •Operators are used to operate on values. There are four classifications of operators: • > Arithmetic • > Assignment • > Comparison • > Logical 27
  • 32. PHP Conditional Statements •> Very often when you write code, you want to perform different actions for different decisions. •> You can use conditional statements in your code to do this. •> In PHP we have the following conditional statements... 32
  • 33. PHP Conditional Statements •> if statement - use this statement to execute some code only if a specified condition is true •> if...else statement - use this statement to execute some code if a condition is true and another code if the condition is false •> if...elseif....else statement - use this statement to select one of several blocks of code to be executed •> switch statement - use this statement to select one of many blocks of code to be executed 33
  • 34. PHP Conditional Statements •The following example will output "Have a nice weekend!" if the current day is Friday: 34
  • 35. PHP Conditional Statements •Use the if....else statement to execute some code if a condition is true and another code if a condition is false. 35
  • 36. PHP Conditional Statements •If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces { } 36
  • 37. PHP Conditional Statements •The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!": 37
  • 38. PHP Conditional Statements •Use the switch statement to select one of many blocks of code to be executed. 38
  • 39. PHP Conditional Statements •For switches, 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. 39
  • 41. PHP Arrays •> An array variable is a storage area holding a number or text. The problem is, a variable will hold only one value. •> An array is a special variable, which can store multiple values in one single variable. 41
  • 42. PHP Arrays •If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: 42
  • 43. 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 best solution here is to use an array. •> An array can hold all your variable values under a single name. And you can access the values by referring to the array name. •> Each element in the array has its own index so that it can be easily accessed. 43
  • 44. PHP Arrays • In PHP, there are three kind of arrays: • > Numeric array - An array with a numeric index • > Associative array - An array where each ID key is associated with a value • > Multidimensional array - An array containing one or more arrays 44
  • 45. PHP Numeric Arrays •> A numeric array stores each array element with a numeric index. •> There are two methods to create a numeric array. 45
  • 46. PHP Numeric Arrays •In the following example the index is automatically assigned (the index starts at 0): •In the following example we assign the index manually: 46
  • 47. PHP Numeric Arrays •In the following example you access the variable values by referring to the array name and index: •The code above will output: 47
  • 48. PHP Associative Arrays •> With an associative array, each ID key is associated with a value. •> When storing data about specific named values, a numerical array is not always the best way to do it. •> With associative arrays we can use the values as keys and assign values to them. 48
  • 49. PHP Associative Arrays •In this example we use an array to assign ages to the different persons: •This example is the same as the one above, but shows a different way of creating the array: 49
  • 51. PHP Multidimensional Arrays •In a multidimensional array, each element in the main array can also be an array. •And each element in the sub-array can be an array, and so on. 51
  • 55. 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 lines in a script we can use loops to perform a task like this. •> In PHP, we have the following looping statements: 55
  • 56. PHP Loops •> while - loops through a block of code while a specified condition is true •> do...while - loops through a block of code once, and then repeats the loop as long as a 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 56
  • 57. PHP Loops - While •The while loop executes a block of code while a condition is true. The example below defines a loop that starts with •i=1. The loop will •continue to run as •long as i is less •than, or equal to 5. •i will increase by 1 •each time the loop •runs: 57
  • 58. PHP Loops - While 58
  • 59. PHP Loops – Do ... While •The do...while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true. •The next example defines a loop that starts with i=1. It will then increment i with 1, and write some output. Then the condition is checked, and the loop will continue to run as long as i is less than, or equal to 5: 59
  • 60. PHP Loops – Do ... While 60
  • 61. PHP Loops – Do ... While 61
  • 62. PHP Loops - For 62
  • 63. PHP Loops - For • Parameters: • > init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop) • > condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. • > increment: Mostly used to increment a counter (but can be any code to be executed at the end of the loop) 63
  • 64. PHP Loops - For •The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs: 64
  • 65. PHP Loops - For 65
  • 66. PHP Loops - Foreach •For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value. 66
  • 67. PHP Loops - Foreach •The following example demonstrates a loop that will print the values of the given array: 67
  • 68. PHP Loops - Foreach 68
  • 69. PHP Functions •> We will now explore how to create your own functions. •> To keep the script from being executed when the page loads, you can put it into a function. •> A function will be executed by a call to the function. •> You may call a function from anywhere within a page. 69
  • 70. PHP Functions •A function will be executed by a call to the function. •> Give the function a name that reflects what the function does •> The function name can start with a letter or underscore (not a number) 70
  • 71. PHP Functions •A simple function that writes a name when it is called: 71
  • 72. PHP Functions - Parameters • Adding parameters... • > To add more functionality to a function, we can add parameters. A parameter is just like a variable. • > Parameters are specified after the function name, inside the parentheses. 72
  • 73. PHP Functions - Parameters 73
  • 74. PHP Functions - Parameters 74
  • 75. PHP Functions - Parameters This example adds different punctuation. 75
  • 76. PHP Functions - Parameters 76
  • 77. PHP Forms - $_GET Function •> The built-in $_GET function is used to collect values from a form sent with method="get". •> Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send (max. 100 characters). 77
  • 78. PHP Forms - $_GET Function Notice how the URL carries the information after the file name. 78
  • 79. PHP Forms - $_GET Function •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) 79
  • 80. PHP Forms - $_GET Function •> When using method="get" in HTML forms, all variable names and values are displayed in the URL. •> This method should not be used when sending passwords or other sensitive information! •> However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. •> The get method is not suitable for large variable values; the value cannot exceed 100 chars. 80
  • 81. PHP Forms - $_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). 81
  • 82. PHP Forms - $_POST Function And here is what the code of action.php might look like: 82
  • 83. PHP Forms - $_POST Function •Apart from htmlspecialchars() and (int), it should be obvious what this does. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can't inject HTML tags or Javascript into your page. •For the age field, since we know it is a number, we can just convert it to an integer which will automatically get rid of any stray characters. The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP. 83
  • 84. PHP Forms - $_POST Function • When to use 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. • > However, because the variables are not displayed in the URL, it is not possible to bookmark the page. 84
  • 85. Introduction to Database & MySQL • Using MySQL from PHP 85
  • 86. Database •A structured collection of data •Contains 1 or more Tables db1 db1.table_1 db1.table_2 db1.table_3 db1.table_4 86
  • 87. Table •Tables contain records •Records contain fields •Fields have values 87
  • 88. Creating a Database Syntax: CREATE DATABASE dbname; Example: CREATE DATABASE training; 88
  • 89. Using a Database Syntax: USE dbname; Example: USE training; 89
  • 90. Creating a Table Syntax: CREATE TABLE table_name ( field1_name field_spec, field2_name field_spec ); Example: CREATE TABLE student ( st_id bigint primary key auto_increment, st_fname varchar(100), st_age tinyint unsigned ); 90
  • 91. Querying a Table Syntax: SELECT <field_list> FROM <table_name> [ WHERE <condition> ]; Example: SELECT * FROM student; SELECT * FROM student WHERE st_age > 20; 91
  • 92. Inserting a Record Syntax: INSERT INTO `table_name` (<fieldlist>) VALUES (<valuelist>}; Example: INSERT INTO student (st_fname, st_age) VALUES ( ‘Ahmad Albab’, 20 ); 92
  • 93. Updating a Record Syntax: UPDATE table_name SET <field value list> [ WHERE <condition> ]; Example: UPDATE student SET st_fname = ‘Jat’, st_age = 22 WHERE st_id = 1; 93
  • 94. Deleting a Record or Records Syntax: DELETE FROM table_name [ WHERE <condition> ]; Example: DELETE FROM student WHERE st_id = 2; DELETE FROM student WHERE st_age < 18; 94
  • 95. PHP Functions for MySQL PHP Function Description mysql_connect() Connect to a MySQL database server mysql_select_db() Make a database active mysql_query() Execute SQL statement on active database mysql_fetch_array() Fetch a row from query result and return as data as an array of fields and values mysql_insert_id() Returns the last inserted ID from an auto_increment field mysql_error() Returns the last MySQL error message. 95
  • 96. mysql_connect() Syntax: resource mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]]); Example: $dbh = mysql_connect( ‘localhost’, ‘root’, ‘’ ); 96
  • 97. mysql_connect() • mysql_connect() • The mysql_connect()function opens a non-persistent MySQL connection. • This function returns the connection on success, or FALSE and an error on failure. You can hide the error output by adding an '@' in front of the function name. • Syntax • mysql_connect(server,user,pwd,newlink,clientfla g) 97
  • 98. mysql_connect() Parameter Description server Specifies the server to connect to user Specifies the username to log in with. pwd Specifies the password to log in with. newlink If a second call is made to mysql_connect() with the same arguments, no new connection will be established; instead, the identifier of the already opened connection will be returned clientflag •MYSQL_CLIENT_SSL - Use SSL encryption •MYSQL_CLIENT_COMPRESS - Use compression protocol •MYSQL_CLIENT_IGNORE_SPACE - Allow space after function names •MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout seconds of inactivity before closing the connection 98
  • 99. MySQL Connectivity • Example: • <?php $con = mysql_connect("localhost","mysql_user","mysq l_pwd"); if (!$con){ die('Could not connect: ‘.mysql_error()); } echo 'Connected successfully'; mysql_close($con); • ?> 99
  • 100. MySQL Connectivity • mysql_close() • The mysql_close() function closes a non-persistent MySQL connection. • This function returns TRUE on success, or FALSE on failure. • Syntax: • mysql_close(connection) Parameter Description connection Specifies the MySQL connection to close. If not specified, the last connection opened by mysql_connect() is used. 100
  • 101. Try out following example to open and close a database connection • <?php • $dbhost = 'localhost:3036'; • $dbuser = 'guest'; • $dbpass = 'guest123'; • $conn = mysql_connect($dbhost, $dbuser, $dbpass); • if(! $conn ) { • die('Could not connect: ' . mysql_error()); } • echo 'Connected successfully'; • mysql_close($conn);?> 101
  • 102. mysql_select_db() Syntax: bool mysql_select_db ( string database_name [, resource link_identifier] ) Example: $stat = mysql_select_db( ‘training’, $dbh ); 102
  • 103. mysql_select_db() • mysql_select_db() • The mysql_select_db() function sets the active MySQL database. • This function returns TRUE on success, or FALSE on failure. • Syntax: • mysql_select_db(database,connection) Parameter Description database Required. Specifies the database to select. connection Optional. Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used. 103
  • 104. mysql_select_db() • <?php $con = mysql_connect("localhost", “root", “admin"); if (!$con){ die('Could not connect: '. mysql_error()); } $db_selected = mysql_select_db("test_db", $con); if (!$db_selected){ die ("Can't use test_db : “. mysql_error()); } mysql_close($con); • ?> 104
  • 105. Example showing you how to select a database • <?php • $dbhost = 'localhost:3036'; • $dbuser = 'guest'; • $dbpass = 'guest123'; • $conn = mysql_connect($dbhost, $dbuser, $dbpass); • if(! $conn ) { • die('Could not connect: ' . mysql_error()); • } • echo 'Connected successfully'; • mysql_select_db( 'test_db' ); • mysql_close($conn); • ?> 105
  • 106. mysql_query() Syntax: resource mysql_query ( string query [, resource link_identifier] ) Example: $rh = mysql_query( ‘SELECT * FROM student’, $dbh ); 106
  • 107. mysql_query() • mysql_query() • The mysql_query() function executes a query on a MySQL database. • This function returns the query handle for SELECT queries, TRUE/FALSE for other queries, or FALSE on failure. • Syntax • mysql_query(query,connection) Parameter Description query Required. Specifies the SQL query to send (should not end with a semicolon) connection Optional. Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used. 107
  • 108. Try out following example to create a database • <?php • $dbhost = 'localhost:3036'; • $dbuser = 'root'; • $dbpass = 'rootpassword'; • $conn = mysql_connect($dbhost, $dbuser, $dbpass); • • if(! $conn ) { • die('Could not connect: ' . mysql_error()); • } • echo 'Connected successfully'; • 108
  • 109. Create a database Cont,,,,,, • $sql = 'CREATE Database test_db'; • $retval = mysql_query( $sql, $conn ); • if(! $retval ) { • die('Could not create database: ' . mysql_error()); • } • echo "Database test_db created successfullyn"; • mysql_close($conn); • ?> 109
  • 110. MySQL Connectivity • <?php $con = mysql_connect("localhost",”root",”admin"); if (!$con){ die('Could not connect: ' . mysql_error()); } $sql = "CREATE DATABASE my_db"; if (mysql_query($sql,$con)){ echo "Database my_db created"; } else{ echo "Error creating database:" . mysql_error(); } • ?> 110
  • 111. MySQL Connectivity • <?php $con = mysql_connect("localhost", “root", “admin"); if (!$con){ die('Could not connect: '. mysql_error()); } $db_selected = mysql_select_db("test_db", $con); if (!$db_selected){ die ("Can't use test_db : “. mysql_error()); } • $sql="SELECT * FROM Person where name=‘$uname’"; mysql_query($sql,$con); mysql_close($con); • ?> 111
  • 112. mysql_fetch_array() Syntax: array mysql_fetch_array ( resource result [, int result_type] ) Example: $row = mysql_fetch_array( $rh ); 112
  • 113. •mysql_fetch_array() • mysql_fetch_array() • The mysql_fetch_array() function returns a row from a recordset as an associative array and/or a numeric array. • This function gets a row from the mysql_query() function and returns an array on success, or FALSE on failure or when there are no more rows. • Syntax • mysql_fetch_array(data,array_type) 113
  • 114. mysql_fetch_array() Parameter Description data Required. Specifies which data pointer to use. The data pointer is the result from the mysql_query() function array_type Optional. Specifies what kind of array to return.Possible values: •MYSQL_ASSOC - Associative array •MYSQL_NUM - Numeric array •MYSQL_BOTH - Default. Both associative and numeric array 114
  • 115. mysql_fetch_row() • mysql_fetch_row() • The mysql_fetch_row() function returns a row from a recordset as a numeric array. • This function gets a row from the mysql_query() function and returns an array on success, or FALSE on failure or when there are no more rows. • Syntax • mysql_fetch_row(data) Parameter Description data Required. Specifies which data pointer to use. The data pointer is the result from the mysql_query() function 115
  • 116. mysql_fetch_row() • <?php • echo "<table>"; • while ($row = mysql_fetch_row($result)) { • echo "<tr><td>".$row[0] ."</td><td>".$row[1]. • "</td><td>".$row[2]."</td><td>". • $row[3]."</td></tr>"; • } • echo "</table>"; • ?> 116
  • 117. mysql_fetch_array() • <?php • echo "<table>"; • while ($row = mysql_fetch_array($result)) { • echo "<tr><td>{$row[‘ID’]} </td><td>{$row[1]} • </td><td>{$row[2]}</td><td> • ${row[‘mailid’]}</td></tr>"; • } • echo "</table>"; • ?> 117
  • 118. mysql_insert_id() Syntax: int mysql_insert_id( [resource link_identifier] ) Example: $newId = mysql_insert_id( $dbh ); 118
  • 119. mysql_error() Syntax: string mysql_error( [resource link_identifier] ) Example: $errMsg = mysql_error( $dbh ); 119
  • 120. Include Files • include “header.php”; • include (“footer.php”); • This inserts files; the code in files will be inserted into current code. • require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. • In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue. 120
  • 121. Include Files • The include_once statement includes and evaluates the specified file during the execution of the script. • This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again. • The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again 121
  • 122. PHP - Forms <?php if ($_POST["submit"]) echo "<h2>You clicked Submit!</h2>"; else if ($_POST["cancel"]) echo "<h2>You clicked Cancel!</h2>"; ?> <form action="form.php" method="post"> <input type="submit" name="submit" value="Submit"> <input type="submit" name="cancel" value="Cancel"> </form> 122
  • 123. PHP - Forms <?php … $term=$_REQUEST[“sterm”]; … ?> <form action="form.php" method="post"> <input type=“text" name=“sterm" value=“<?= $term ?>"> </form> 123
  • 124. Cookies • The setcookie() function is used to create cookies. Should be called before <html> tag. • setcookie(name, [value], [expire], [path], [domain], [secure]); • <?php setcookie("uname", $name, time()+36000); ?> • This sets a cookie named "uname" - that expires after ten hours. • Either a blank value or a time in the past makes the cookie expired. 124
  • 125. Cookies • To access a cookie, refer to the cookie name as a variable or use $_COOKIE array. The isset() checks whether the cookie is set or not <html> <body> <?php if (isset($uname))// isset($_Cookie[$uname]) echo "Welcome " . $_Cookie[$uname]. "!<br />"; else echo "You are not logged in!<br />"; ?> ?> </body> </html> 125
  • 126. Cookies •Benefit of Cookies • Cookies are used for authenticating, tracking, and maintaining specific information about users • Personalised home pages • Electronic shopping carts. 126
  • 127. Why use sessions • A normal HTML website will not pass data from one page to another • All information is forgotten when a new page is loaded • Many websites need to pass user data from one page to another • for tasks like a shopping cart, which requires data(the user's selected product) to be remembered from one page to the next • Using PHP sessions is one solution. 127
  • 128. Sessions • The session_start() function is used to create a session. Should be called before • <html> tag. <?php session_start(); ?> 128
  • 129. Sessions • <?php • session_start(); • if (!isset($_SESSION['count'])) • $_SESSION['count'] = 0; • else • $_SESSION['count']++; • ?> 129
  • 130. Sessions • session_unregister(´varname´); unregisters a session variable • session_destroy() destroys a session 130
  • 131. mysql_connect() & Mysqli_connect • MySQLi provides a object-oriented way for accessing MySQL databases. • if you use mysql_query(), • you should use mysql_connect() to connect to your server. • Mysqli_connect is the newer version of mysql library 131