0% found this document useful (0 votes)
27 views

Presentation IT ext

server-side ppt

Uploaded by

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

Presentation IT ext

server-side ppt

Uploaded by

yuti6211
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 149

Unit One

Server Side Scripting Basics


Introduction to server-side scripting
• Server-side scripting is a web
server technology in which a user's request is
verified by running a script directly on the web
server to generate dynamic web pages.
• It is used to create dynamic web pages
• Unlike client side scripting, the code is secure as
it cannot be viewed on the client
• The use of server-side scripting is often less
visible to users.
• It is mostly used for content management,
where the site's content is stored in a database
and presented to the user on request. 1
DYNAMIC WEBSITE
• A dynamic website is a website that changes
depending upon what your visitors want to see.
• A dynamic website works in conjunction with a
database and server side scripts to create your
pages on the fly.
• That means that when someone types a URL into
their browser the website is created by the “scripts”
retrieving the required information from the
database.
• It’s really not important at this point to concern
yourself with trying to figure out what a database or
server side scripts are.
• The main thing to keep in mind is that a dynamic
website has the capability to be changed as needed2
with minimal effort.
Advantages of a Dynamic Website
• Can be quickly and easily updated.
• Visitor friendly – facilitates a two way
flow of information.
Disadvantages of a Dynamic website
• Can be more costly to develop.
• More moving parts increases the risk of
something going wrong.

3
Static web pages
• The server contain HTML files
• These are served to the client browser on
request
• The local browser may have some
interaction via client-side scripting
(JavaScript)
• The HTML pages are fixed and cannot be
altered to match individuals requests
• HTML pages are generated when they are
requested
• The basic page is done in a scripting
language and uses HTML and CSS to
determine static content and appearance 4
Client sides
• Client-side scripting offers an easy way to
provide additional functionality and flexibility to
your project.
• HTML is very limited; it's main purpose is to
display and format content.
• It allows little or no interaction with the visitors
of your site.
• Scripting technologies like JavaScript, JScript,
VBScript and others are used on many sites to
add extra functionality to a web site.
• Ranging from simple mouse over image effects,
animation and form field validation to complex
dynamic menu systems, these scripts enhance
the functionality and user experience. 5
Server sides
• Server-side technologies like PHP, ASP, JSP,
Perl and many others have nearly become
a requirement for successful web sites
today.
• Like client-side scripting, server-side
scripting also enhances the functionality of
your site.
• Forums, polls, guest books, searches and
many other uses of this technology allow
for far more interaction with your visitors
than with HTML alone.
• And server-side scripting can be very
useful in site maintenance. 6
• By creating a content management
system (or "CMS") you can provide
yourself and your colleagues with an
easy and efficient way to update your
site.
– Server-side scripts are run on the server.
– This reduces the amount of bugs or
compatibility issues since the code is run
on one server using one language and
hosting software.
– Server-side programming can also be
encrypted when users send form variables,
protecting users against any hack
attempts. 7
Server-side scripts
• Executed on server
• Generate custom response for clients
• Provides programmers greater flexibility
• Can use centralised server resources e.g databases
• Contains greater programmatic capabilities than
client-side equivalents
• Access to server-side software that extends server
functionality
• Password protection
• Browser sniffing/customization
• Form processing
• Building and displaying pages created from a
database
– Programs running on a Web server create Web pages
before sending them back to the requesting Web clients8
• Server side scripting languages include
– Common Gateway Interface (CGI)
– Fast CGI
– Mod Perl
– Active Server Pages (ASP)
– Personal Home Pages (PHP)
– Cold Fusion
– Java Servlets
– Java Server Page (JSP)

9
Client-side scripting
– Validates user input
– Accesses the browser
– Enhances Web pages with ActiveX® controls,
applets, etc.
– Manipulates browser documents
• Client-side validation
– Reduces number of requests that need to be
passed to server
– Good for
• User aids (drop downs, hover etc)
• Local navigation
• Client-side scripting limitations
– Browser dependency
– Viewable to users through View Source
command 10
Differences between client side and
server side scripting
• The main difference between client and
server-side scripting lies in the place
and way it is executed.
• Client side scripts are downloaded by
the browser, interpreted by the
browser, and executed by the browser,
depending on the memory, CPU speed
and internet connection when dealing
with animation, and even the video
card in use on your visitors' computer.
11
• Server-side scripts run on the server
and depend on the memory and CPU
speed of the server. This difference is of
vital importance when making a choice
between client and server-side scripting
solutions for your project.

12
• Server-side scripting has to be
supported by the server that will host
your site.
• While most decent web hosting
companies support at least one server-
side scripting language, many free web
hosts may not.
• If your project requires server-side
scripting, or if you are thinking of taking
your first steps into this world, make
sure your new or current host supports
it.
13
Common Features
• All server-side frameworks share a common set
of features
– Read data submitted by the user
– Generate HTML dynamically based on user input
– Determine information about the client browser
– Access database systems
– Exploit the HTTP protocol
Decision Points
• When evaluating which server-side technology to use,
you need to consider a number of critical factors
– Ease of development
• How easily can you build new applications
– Performance
• How fast can the technology respond to queries
– Scalability
• Can the technology scale to thousands, even millions of users?
– Security
• Are there any inherent security vulnerabilities?
14
ASP
• Active Server Pages (ASP)
• a server-side scripting environment from
Microsoft
• Uses a file extension of .asp
• Scripts are usually written in VBScript
• ASP will normally run only on Microsoft servers
ASP.NET
• The successor to Microsoft's ASP
• Allows programmers to create web applications
using any scripting or programming language
supported by the .NET Framework.
• The main building blocks are pages known
as web forms, which contain definitions for
server-side Web Controls and User Controls,
15
• Web forms have the file extension .aspx
ColdFusion Markup Language (CFML)
• A scripting language originally introduced by Adobe
Systems in 1995
• Enables web developers to embed database
commands and other server-side scripting
elements within standard HTML or XHTML
• Pages in a ColdFusion web application are pre-
processed by the ColdFusion Application
Server when requested by a client browser
Perl
• A high-level, interpreted programming language
• a procedural programming language loosely based
on C
• Used for the creation of web applications,
especially those where database access is
required.
16
• Perl is free software
Java Server Pages (JSP)
• A Java technology similar to ASP
• Used to create dynamically generated
web pages by embedding Java
programming code in HTML or XHTML
documents
• A Java Server Page is compiled into a
Java servlet by an application server,
rather than being interpreted
• A servlet is a Java program that
executes on the server to create
dynamic web pages.
17
PHP
• a widely-used scripting language
• PHP is free software released
• PHP code can be embedded into HTML or XHTML
documents
• It is executed on the server to generate dynamic web content.
• PHP is frequently used together with MySQL, and is one of
the key technologies
What we will use for this unit

Web server scripts written in PHP

Database commands written in SQL (structured query
language)

Client scripts written in JavaScript

Apache Web server

MySQL database managed with PHPMyAdmin 18
What is PHP?
PHP stands for Hypertext Preprocessor
PHP is a server-side scripting language, like ASP
PHP scripts are executed on the server
PHP supports many databases (MySQL, Informix,
Oracle, Sybase, Solid, PostgreSQL, Generic ODBC,
etc.)
PHP is an open source software (OSS) developed by
volunteers
PHP is free to download and use
Provides simple and powerful database access and
tools
Good for Rapid Application Development 19
What is a PHP File?
PHP files may contain text, HTML tags and
scripts
Scripts in a PHP file are executed on the
server.
PHP files are returned to the browser as plain
HTML
PHP files have a file extension of ".php",
".php3", or ".phtml"

20
Why PHP?
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

21
• You cannot view the PHP source code by
selecting "View source" in the browser
• you will only see the output from the PHP
file, which is plain HTML.
• This is because the scripts are executed on
the server before the result is sent back to the
browser.

22
Basic PHP Syntax
• A PHP file normally contains HTML tags,
just like an HTML file, and some PHP
scripting code.
• Below, we have an example of a simple
PHP script which sends the text "Hello
World" to the browser:
<html>
<body>
<?php echo "Hello World"; ?>
</body>
</html>
23
• A PHP scripting block always starts with <?
php and ends with ?>
• A PHP scripting block can be placed
anywhere in the document.
• Each code line in PHP must end with a
semicolon. The semicolon is a separator and is
used to distinguish one set of instructions from
another.
• There are two basic statements to output text
with PHP: echo and print.

24
Variables in PHP
• All variables in PHP start with a $ sign symbol.
Variables may contain strings, numbers, or arrays.
• PHP is not a strongly typed language. The same variable
can hold strings or numbers. They don`t have to be
declared, just use them or reuse them:
• Below, the PHP script assigns the string "Hello World"
to a variable called $txt:
<html>
<body>
<?php
$txt="Hello World";
echo $txt;
?>
</body>
</html> 25
Numbers
• All the rule about precedence apply
Strings
• To assign a string to a variable, you must use quotes.
Double quotes allow for variable substitution and escape
sequences
• Ex.
$first_name=‟Mimi‟;
$greeting1 = “Hello, my first name is” . $first_name;
echo $greeting1;
$last_name=”Opkins”;
$greeting2=‟Hello, my last name is”. $last_name.‟;
echo $greeting2;
• Output:
Hello, my first name is Mimi.
26
Hello, my last name is Opkins.
• Note that: To concatenate two or more
variables together, use the dot (.) operator:
<html>
<body>
<?php
$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2 ;
?>
</body>
</html>

27
Comments in PHP
• In PHP, we use // to make a single-line comment or /* and
*/ to make a large comment block.
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>
28
PHP Operators
• Operators are used to operate on values.
• This section lists the different operators
used in PHP.
1. Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
29
2. Assignment Operators
Operator Example Is The Same As
= X=Y X=Y
+= X+=Y X=X+Y

-= X-=Y X=X-Y

*= X*=Y X=X*Y

/= X/=Y X=X/Y

%= X%=Y X=X%Y

30
3. Comparison Operators
Operator Examples
== 5==8 returns False
!= 5!=8 returns True

> 5>8 returns False

< 5<8 returns True

>= 5>=8 returns False

<= 5<=8 returns True

31
4. Logical Operators
Operator Description Example

&& AND x=6


y=3
(x < 10 && y > 1)
returns true

II OR x=6
y=3
(x ==5 II y == 5) returns
false

! NOT x=6
y=3
!(x == y) returns true

32
Control Flow Structure
I. PHP Conditional Statements
• Conditional statements in PHP are used to
perform different actions based on different
conditions.
• 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.

33
In PHP we have two conditional statements:
 if (...else) statement - use this statement if you
want to execute a set of code when a
condition is true (and another if the condition
is not true)
switch statement - use this statement if you
want to select one of many sets of lines to
execute

34
A. The If Statement
If you want to execute some code if a
condition is true and another code if a
condition is false, use the if....else statement.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

35
• The following example will output "Have a nice weekend!" if the current day is Friday:
< HTML>
< BODY>
< ?PHP
$D=DATE("D");
IF ($D=="FRI") ECHO "HAVE A NICE WEEKEND!";
?>
< /BODY>
< /HTML>
• The following example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!":
< html>
< body>
< ?php
$d=date("D");
if ($d=="Fri")
{
echo "Have a nice weekend!";
}
else
{
echo "Have a nice day!";
}
?>
< /BODY> 36
• 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!":
< HTML>
< BODY>
< ?PHP
$D=DATE("D");
IF ($D=="FRI")
{
ECHO "HAVE A NICE WEEKEND!";
}
ELSEIF ($D=="SUN")
{
ECHO "HAVE A NICE SUNDAY!";
}
ELSE
{
ECHO "HAVE A NICE DAY!";
}
?>
< /BODY>
37
< /HTML>
B. The Switch Statement
 If you want to select one of many blocks of code to be executed,
use the Switch statement.
Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
//if expression is different from both label1 and label2;
}
This is how it works: First we have a single expression n (most often a
variable), that is evaluated once. 38
• 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.
EXAMPLE
< HTML>
< BODY>
< ?PHP
$X=1;
SWITCH ($X)
{
CASE 1:
ECHO "NUMBER 1";
BREAK;
CASE 2:
ECHO "NUMBER 2";
BREAK;
CASE 3:
ECHO "NUMBER 3";
BREAK;
DEFAULT:
ECHO "NO NUMBER BETWEEN 1 AND 3";
}
?>
39
< /BODY>
II. PHP Looping
 Looping statements in PHP are used to execute the same
block of code a specified number of times
 Looping is Very often when you write code, you want the
same block of code to run a number of times. You can use
looping statements in your code to perform this.
In PHP we have the following looping statements:
• while - loops through a block of code as long as a specified
condition is true
• do...while - loops through a block of code once, and then
repeats the loop as long as a special 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 40
A. The while Statement
 The while statement will execute a block of code if and as long a
condition is true.
Syntax
while (condition)
code to be executed;
Example:
< HTML>
< BODY>
< ?PHP
$I=1;
WHILE($I<=5)
{
ECHO "THE NUMBER IS " . $I . "<BR />";
$I++;
}
?>
< /BODY> 41
< /HTML>
B. The do...while Statement
 The do...while statement will execute a block of code at least once - it then will repeat
the loop as long as a condition is true.
Syntax
do
{
code to be executed;
}
While (condition);
< html>
< body>
< ?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<=5);
?>
< /body>
< /html> 42
C. The for Statement
 The for statement is used when you know how many times
you want to execute a statement or a list of statements.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
Note: The for statement has three parameters. The first
parameter is for initializing variables, the second parameter
holds the condition, and the third parameter contains any
increments required to implement the loop. If more than
one variable is included in either the initialization or the
increment section, then they should be separated by
commas. The condition must evaluate to true or false. 43
< HTML>
< BODY>
< ?PHP
FOR ($I=1; $I<=5; $I++)
{
ECHO "THE NUMBER IS " . $I . "<BR />";
}
?>
< /BODY>
< /HTML>

44
D. The foreach Statement
 Loops over the array given by the parameter. On each loop, the value of the current element is
assigned to $value and the array pointer is advanced by one - so on the next loop, you'll be
looking at the next element.
Syntax
foreach (array as value)
{
code to be executed;
}
Example
The following example demonstrates a loop that will print the values of the given array:
<html>
<body>
<?php
$arr=array("one", "two", "three");
foreach ($arr as $value)
{
echo "Value: " . $value . "<br />";
}
?>
</body>
45
</html>
Arrays
 The most inconvenient thing about a variable is that you
can only store one value at a time.
 Arrays are special types that allow variables to overcome
this limitation, so you can store as many values as you
want in the same variable.
For example, instead of having two variables “$number1”
and “$number2”, you could have an array “$numbers”
that will hold both values.
 array can store two values or two hundred values,
without having to define other variables.
 PHP indexes all the values within an array using a
number or a string, so you will know which of the values
you’re using.
46
 Working with arrays is easy. You can process each item
one after another, or you could just take one at random.
 Each item in an array is commonly referred to as an
element.
 These elements can be accessed directly via their index.
 By default, PHP starts indexing elements numerically,
from zero, and increments the element’s index with
each new addition, so keep in mind that the index of
the last elements in a numerically indexed array is
always the total number of elements minus one.
 Indexing arrays by string can be useful in cases where
you need to store both names and values.

47
• In PHP, there are three kind of arrays:
1. NUMERIC ARRAY - AN ARRAY WITH A NUMERIC INDEX
2. ASSOCIATIVE ARRAY - AN ARRAY WHERE EACH ID KEY IS
ASSOCIATED WITH A VALUE
3. MULTIDIMENSIONAL ARRAY - AN ARRAY CONTAINING ONE OR
MORE ARRAYS
Numeric Arrays
• A numeric array stores each array element with a numeric index.
• There are two methods to create a numeric array.
1. In the following example the index are automatically assigned (the
index starts at 0):
$CARS=ARRAY("SAAB","VOLVO","BMW","TOYOTA");
2. In the following example we assign the index manually:
$CARS[0]="SAAB";
$CARS[1]="VOLVO";
$CARS[2]="BMW";
$CARS[3]="TOYOTA"; 48
EXAMPLE
• In the following example you access the variable
values by referring to the array name and index:
• < ?PHP
$CARS[0]="SAAB";
$CARS[1]="VOLVO";
$CARS[2]="BMW";
$CARS[3]="TOYOTA";
ECHO $CARS[0] . " AND " . $CARS[1] . " ARE
SWEDISH CARS.";
?>
• The code above will output:
SAAB AND VOLVO ARE SWEDISH CARS. 49
Associative Arrays
• 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.
EXAMPLE 1
• In this example we use an array to assign ages to the different
persons:
$AGES = ARRAY("PETER"=>32, "QUAGMIRE"=>30, "JOE"=>34);
EXAMPLE 2
• This example is the same as example 1, but shows a different
way of creating the array:
$AGES['PETER'] = "32";
$AGES['QUAGMIRE'] = "30";
$AGES['JOE'] = "34"; 50
• The ID keys can be used in a script:
< ?PHP
$AGES['PETER'] = "32";
$AGES['QUAGMIRE'] = "30";
$AGES['JOE'] = "34";
ECHO "PETER IS " . $AGES['PETER'] . " YEARS
OLD.";
?>
• The code above will output:
PETER IS 32 YEARS OLD.

51
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.
EXAMPLE
• In this example we create a multidimensional array, with automatically assigned ID keys:
• $FAMILIES = ARRAY("GRIFFIN"=>ARRAY("PETER","LOIS","MEGAN"),
"QUAGMIRE"=>ARRAY("GLENN"),"BROWN"=>ARRAY("CLEVELAND","LORETTA","JUNIOR"));
• The array above would look like this if written to the output:
ARRAY([GRIFFIN] => ARRAY(
[0] => PETER
[1] => LOIS
[2] => MEGAN
)
[QUAGMIRE] => ARRAY
(
[0] => GLENN
)
[BROWN] => ARRAY
(
[0] => CLEVELAND
[1] => LORETTA
[2] => JUNIOR
) 52
)
PHP Functions
• Functions are the most important part of any
programming language
• Functions are pieces of code that accept values and
produce results.
• While there are functions that you don’t need to supply
any values to, a function which does nothing is pointless.
• Functions come in handy when you’re writing repetitive
code, and you’re looking to use the same code in other
scripts.
• A function is a block of code that is not immediately
executed, but can be called by your scripts when needed.
• Functions can either be built-in or defined by the user.

53
A. User defined PHP Function
SYNTAX
FUNCTION FUNCTION_NAME()
{
CODE TO BE EXECUTED;
}
• A function will be executed by a call to the function.
• You may call a function from anywhere within a
page.
PHP function guidelines:
• Give the function a name that reflects what the
function does
• The function name can start with a letter or
underscore (not a number)
54
EXAMPLE
• A simple function that writes my name when it is called:
< HTML>
< BODY>
< ?PHP
FUNCTION WRITENAME()
{
ECHO "KAI JIM REFSNES";
}

ECHO "MY NAME IS ";


WRITENAME();
?>

< /BODY>
< /HTML>
55
B. PHP Built-in Functions
• The real power of PHP comes from its functions.
• In PHP - there are more than 700 functions
available.
1. PHP Information
The phpinfo() function is used to output PHP
information.
• This function is useful for trouble shooting,
providing the version of PHP, and how it is
configured.

56
Example
<html>
<body>
<?php
// Show all PHP information
phpinfo();
?>
<?php
// Show only the general information
phpinfo(INFO_GENERAL);
?>
</body>
</html>
57
3. PHP Date() Function
• The date() function is used to format a time or a date.
Syntax
date (date_format[,int timestamp])
• This function returns a string formatted according to the
specified format.
PHP Date() - Format the Date
• The required format parameter in the date() function
specifies how to format the date/time.
Here are some characters that can be used:
• D - Represents the day of the month (01 to 31)
• M - Represents a month (01 to 12)
• Y - Represents a year (in four digits)

58
• Other characters, like"/", ".", or "-" can also be
inserted between the letters to add additional
formatting:
EXAMPLE 1.
<?PHP
ECHO DATE("Y/M/D") . "<BR />";
ECHO DATE("Y.M.D") . "<BR />";
ECHO DATE("Y-M-D");
?>

59
• Example 2
<?php
//Prints something like: Monday
echo date("l");
//Prints something like: Monday 15th of January 2003
05:51:38 AM
echo date("l F Y h:i:s A");
//Prints something like: Monday the 15th
echo date("l \\t\h\e jS");
?>

60
Character Description
a "am" or "pm"
A "AM" or "PM"
d Day of the month with a leading zero (01-31)
D Three characters that represents the day of the week (Mon-Sun)
F The full name of the month (January-December)
g The hour in 12-hour format without a leading zero (1-12)
G The hour in 24-hour format without a leading zero (0-23)
h The hour in 12-hour format with a leading zero (01-12)
H The hour in 24-hour format with a leading zero (00-23)
i The minutes with a leading zero (00-59)
I "1" if the date is in daylights savings time, otherwise "0"
j Day of the month without a leading zero (1-31)
l The full name of the day (Monday-Sunday)

61
L "1" if the year is a leap year, otherwise "0"
m The month as a number, with a leading zero (01-12)
M Three letters that represents the name of the month (Jan-Dec)
n The month as a number without a leading zero (1-12)
O The difference to Greenwich time (GMT) in hours
r An RFC 822 formatted date (e.g. "Tue, 10 Apr 2005 18:34:07 +0300")
s The seconds with a leading zero (00-59)
S The English ordinal suffix for the day of the month (st, nd, rd or th)
t The number of days in the given month (28-31)
T The local time zone (e.g. "GMT")
U The number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
w The day of the week as a number (0-6, 0=Sunday)
W ISO-8601 week number of year, weeks starting on Monday
Y The year as a 4-digit number (e.g. 2003)
y The year as a 2-digit number (e.g. 03)
z The day of the year as a number (0-366)
62
3. The strlen() function
• The strlen() function is used to return the length of a string.
Let's find the length of a string:
< ?PHP
ECHO STRLEN("HELLO WORLD!");
?>
4. The strpos() function
• The strpos() function is used to search for a character/text
within a string.
• If a match is found, this function will return the character
position of the first match. If no match is found, it will return
FALSE.
• Let's see if we can find the string "world" in our string:
< ?PHP
ECHO STRPOS("HELLO WORLD!","WORLD");
?> 63
PHP $_GET VARIABLE
• In PHP, the predefined $_GET variable is used
to collect values in a form 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.
– Limited to 2,048 characters for the entire URL
– Result page can be bookmarked and cached

64
EXAMPLE
< form action="welcome.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
< input type="submit" />
< /form>
• When the user clicks the "Submit" button, the
URL sent to the server could look something like
this:
• http://www.w3schools.com/welcome.php?fnam
e=Peter&age=37
65
• The "welcome.php" file can now use the $_GET
variable to collect form data (the names of the
form fields will automatically be the keys in the
$_GET array):

WELCOME <?PHP ECHO $_GET["FNAME"]; ?


>.<BR />
YOU ARE <?PHP ECHO $_GET["AGE"]; ?> YEARS
OLD!

66
When to use method="get"?
• When using method="get" in HTML forms, all
variable names and values are displayed in the
URL.
• Note: 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.
• Note: The get method is not suitable for very
large variable values. 67
The $_POST Variable
• The predefined $_POST variable 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).

68
EXAMPLE
< form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
< input type="submit" />
< /form>
• When the user clicks the "Submit" button, the
URL will look like this:
http://www.w3schools.com/welcome.php

69
• The "welcome.php" file can now use the
$_POST variable to collect form data (the names
of the form fields will automatically be the keys
in the $_POST array):
Welcome <?php echo $_POST["fname"]; ?>!
<br />
You are <?php echo $_POST["age"]; ?> years
old.

70
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.

71
The PHP $_REQUEST Variable
• The predefined $_REQUEST variable contains
the contents of both $_GET and $_POST
• The $_REQUEST variable can be used to collect
form data sent with both the GET and POST
methods.
EXAMPLE
Welcome <?php echo $_REQUEST["fname"]; ?>!
<br />
You are <?php echo $_REQUEST["age"]; ?> years
old.
72
Unit 2
HTML Forms and Server Side Scripting

Data Validation
• Data validation is the process of ensuring that computer input is
clean, correct, and useful.
• Typical validation tasks are:
– has the user filled in all required fields?
– has the user entered a valid data?
– has the user entered text in a numeric field?
• Most often, the purpose of data validation is to ensure correct input
to a computer application.
• Validation can be defined by many different methods, and deployed
in many different ways.
• Server side validation is performed by a web server, after input has
been sent to the server.
• Client side validation is performed by a web browser, before input 73
• The HTML form we will be working at in this
chapter, contains various input fields: required
and optional text fields, radio buttons, and a
submit button:
• The validation rules for the form above are as
follows:
Field Validation Rules

Name Required. + Must only contain letters and whitespace

E-mail Required. + Must contain a valid email address (with @ and .)

Website Optional. If present, it must contain a valid URL

Comment Optional. Multi-line input field (textarea)

Gender Required. Must select one


74
The Form Element
• There are two specific attributes that need to be set in the
form tag, action and method:
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
• When the form is submitted, the form data is sent with
method="post".
• What is the $_SERVER["PHP_SELF"] variable?
The $_SERVER["PHP_SELF"] is a super global variable that
returns the filename of the currently executing script.
• So, the $_SERVER["PHP_SELF"] sends the submitted form
data to the page itself, instead of jumping to a different page.
• action defines where the form contents are sent when the
form is submitted; in this case, the value of
$_SERVER["PHP_SELF"].
75
What is the htmlspecialchars() function?
• The htmlspecialchars() function converts special
characters to HTML entities. This means that it will
replace HTML characters like < and > with &lt; and
&gt;. This prevents attackers from exploiting the code
by injecting HTML or Javascript code (Cross-site
Scripting attacks) in forms.
• $_SERVER["PHP_SELF"] exploits can be avoided by
using the htmlspecialchars() function.
• The form code should look like this:
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
• The htmlspecialchars() function converts special
characters to HTML entities. 76
• $_SERVER is an array with entries filled in at PHP run time; the
PHP_SELF key contains the filename of the PHP script that is
being executed. Using $_SERVER["PHP_SELF"] is preferable to
simply hard-coding a location if you want your form to post
back to the same script that generated it since you won’t have
to update the code if you change the script’s name.
• method determines how the form’s contents is submitted.
POST means that the form’s content is sent as part of the
HTTP request’s body. The values are then retrievable in PHP
using the $_POST array.
• The alternative to POST is GET which passes the form’s values
as part of the URL. Values sent using GET are retrievable in
PHP using $_GET. The main difference between the methods
POST and GET is visibility. There are numerous articles on the
web about choosing between them, but my advise is to stick
to POST when using forms unless you have a good reason to
pass user data in a viewable URL. 77
• Here, our PHP validation includes the following steps:
– Checking for empty fields.
– Checking for data filtration.
– Input comparison with Regular expression.
• First, we used PHP empty() function to check for empty fields.
if (empty($_POST["name"]))
{
echo "Name is required";
}
• Second, we pass the non empty value to a user defined function
test_input($data) to filter user input.
// Function for filtering input values.
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data; 78
– Strip unnecessary characters (extra space, tab,
newline) from the user input data (with the PHP
trim() function)
– Remove backslashes (\) from the user input data
(with the PHP stripslashes() function)
• The function test_input() that will do all the
checking for us (which is much more
convenient than writing the same code over
and over again).
• We will name the function test_input().
• Now, we can check each $_POST variable with
the test_input() function, and the script looks
like this: 79
Example
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

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

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
• Third, we applied preg_match() function to the above filtered value to get user80
• Remember that when working with HTML forms:
• All of the form controls must be enclosed within
the form tags.
• The alignment of text and form controls can be
achieved in many ways. CSS is the preferred
option for many, but be prepared to see tables
used for alignment in older HTML.

81
1. PHP - Validate Name
• The code below shows a simple way to check if the
name field only contains letters and whitespace. If
the value of the name field is not valid, then store
an error message:
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space
allowed";
}
• The preg_match() function searches a string for
pattern, returning true if the pattern exists, and
false otherwise. 82
2. PHP - Validate E-mail
• The easiest and safest way to check whether an
email address is well-formed is to use PHP's
filter_var() function.
• In the code below, if the e-mail address is not
well-formed, then store an error message:
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid email format";
}
83
3. PHP - Validate URL
• The code below shows a way to check if a URL
address syntax is valid (this regular expression
also allows dashes in the URL). If the URL
address syntax is not valid, then store an error
message:
$website = test_input($_POST["website"]);
if(!preg_match("/\b(?:(?:https?|ftp):\/\/|
www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
84
PHP - Complete Form Example
• Here is the complete code for the PHP Form Validation
Example:
PHP Source:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = ""; 85
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
} 86
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows
dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?
=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
} 87
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?
>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo
$comment;?></textarea>
88
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo
"checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo
"checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>

89
90
Summary
• Validation is essential, particularly if you are
going to save the data in a database –
remember the old saying, GIGO (Garbage In,
Garbage Out), and you won’t go far wrong. In
this article you have learned how to create a
simple HTML form and validate it with PHP.
Along the way a number of techniques have
been used to re-display user input and display
error messages.

91
UNIT THREE
PHP MYSQL INTRODUCTION
• MySQL is the most popular open-source database
system.
What is MySQL?
• MySQL is a database.
• The data in MySQL is stored in database objects called
tables.
• A table is a collection of related data entries and it
consists of columns and rows.
• Databases are useful when storing information
categorically. A company may have a database with the
following tables: "Employees", "Products", "Customers"
and "Orders". 92
Database Manipulation
• One of the defining features of PHP is the ease with
which you can connect to and manipulate databases.
• PHP implements functions for connecting to a wide
range of databases systems: MySQL, Oracle, MSSQL,
Interbase, dBase, and many more.
• While there are many commercial database systems
which cost thousands of dollars and provide
thousands of components, the Internet community
provides solutions for low-budget users as well.
• MySQL, for example, doesn’t require you to purchase
a license if you don’t use it for commercial activities.

93
• The way PHP talks to the database is simple. First you need
to connect to the database system, which runs as a
daemon (service for Windows) in the background.
• In order to do this, you must have appropriate permissions
to connect to the database server from its owner.
• While you can always install and configure a database
system on your own computer for starters, when it comes
to hosting a web-site you must talk to a hosting company.
• They will open an account for you, and give you the
information on how to connect to the database server.
• Many hosting companies use MySQL, so we’ll focus on
using this database system.
• First, you must use the “mysql_connect()” function along
with the server’s IP, the username and the password
required to connect to the server.
94
Create a Connection to a MySQL Database
• The free MySQL database is very often used
with PHP.
• Before you can access data in a database, you
must create a connection to the database.
• In PHP, this is done with the mysql_connect()
function.
SYNTAX
• MYSQL_CONNECT(SERVERNAME,USERNAME,
PASSWORD);

95
Parameter Description

servername Optional. Specifies the server to connect to.


Default value is "localhost"
username Optional. Specifies the username to log in
with. Default value is “root”
password Optional. Specifies the password to log in
with. Default is ""

Note: There are more available parameters, but the ones listed above are the
most important.

96
EXAMPLE
• In the following example we store the connection in a
variable ($con) for later use in the script. The "die" part
will be executed if the connection fails:
< ?PHP
$CON
=MYSQL_CONNECT("LOCALHOST","PETER","ABC12");
IF (!$CON)
{
DIE('COULD NOT CONNECT: ' . MYSQL_ERROR());
}

// SOME CODE
?>
97
Closing a Connection
• The connection will be closed automatically when the script
ends. To close the connection before, use the mysql_close()
function:
< ?PHP
$CON=MYSQL_CONNECT("LOCALHOST","PETER","ABC12");
IF (!$CON)
{
DIE('COULD NOT CONNECT: ' . MYSQL_ERROR());
}

// SOME CODE

MYSQL_CLOSE($CON);
?>

98
PHP MYSQL CREATE DATABASE AND TABLES
• A database holds one or multiple tables.
Create a Database
• The CREATE DATABASE statement is used to
create a database in MySQL.
SYNTAX
• CREATE DATABASE DATABASE_NAME

99
• To get PHP to execute the statement above we must use the mysql_query()
function. This function is used to send a query or command to a MySQL connection.
EXAMPLE
• The following example creates a database called "my_db":
< ?PHP
$CON = MYSQL_CONNECT("LOCALHOST","PETER","ABC123");
IF (!$CON)
{
DIE('COULD NOT CONNECT: ' . MYSQL_ERROR());
}

IF (MYSQL_QUERY("CREATE DATABASE MY_DB",$CON))


{
ECHO "DATABASE CREATED";
}
ELSE
{
ECHO "ERROR CREATING DATABASE: " . MYSQL_ERROR();
}

MYSQL_CLOSE($CON);
?>

100
Database Tables
• A database most often contains one or more tables.
Each table is identified by a name (e.g. "Customers" or
"Orders"). Tables contain records (rows) with data.
• Below is an example of a table called "Persons":
LASTNAME FIRSTNAME ADDRESS CITY

HASSEN ALI S.WOLLO DESSIE

SAMSON ASSEFA W. GOJAM BAHIRDAR

ASTER KEBEDE SHEWA ADDIS ABABA

• The table above contains three records (one for each


person) and four columns (LastName, FirstName,
Address, and City).
101
Create a Table
• The CREATE TABLE statement is used to create a table in
MySQL.
SYNTAX
CREATE TABLE TABLE_NAME
(
COLUMN_NAME1 DATA_TYPE,
COLUMN_NAME2 DATA_TYPE,
COLUMN_NAME3 DATA_TYPE,
....
)

• We must add the CREATE TABLE statement to the


mysql_query() function to execute the command.
102
EXAMPLE
• The following example creates a table named "Persons", with three columns. The column names will be
"FirstName", "LastName" and "Age":
< ?PHP
$CON = MYSQL_CONNECT("LOCALHOST","PETER","A123");
IF (!$CON)
{
DIE('COULD NOT CONNECT: ' . MYSQL_ERROR());
}

// CREATE DATABASE
IF (MYSQL_QUERY("CREATE DATABASE MY_DB",$CON))
{
ECHO "DATABASE CREATED";
}
ELSE
{
ECHO "ERROR CREATING DATABASE: " . MYSQL_ERROR();
}

// CREATE TABLE
MYSQL_SELECT_DB("MY_DB", $CON);
$SQL = "CREATE TABLE PERSONS
(
FIRSTNAME VARCHAR(15),
LASTNAME VARCHAR(15),
AGE INT
)";

// EXECUTE QUERY
MYSQL_QUERY($SQL,$CON);
103
MYSQL_CLOSE($CON);
• Important: A database must be selected before a table
can be created. The database is selected with the
mysql_select_db() function.
• Note: When you create a database field of type
varchar, you must specify the maximum length of the
field, e.g. varchar(15).
• The data type specifies what type of data the column
can hold.
Primary Keys and Auto Increment Fields
• Each table should have a primary key field.
• A primary key is used to uniquely identify the rows in a
table. Each primary key value must be unique within
the table. Furthermore, the primary key field cannot
be null because the database engine requires a value
to locate the record. 104
• The following example sets the personID field as the
primary key field. The primary key field is often an ID
number, and is often used with the AUTO_INCREMENT
setting. AUTO_INCREMENT automatically increases the
value of the field by 1 each time a new record is added. To
ensure that the primary key field cannot be null, we must
add the NOT NULL setting to the field.
EXAMPLE
$SQL = "CREATE TABLE PERSONS
(
PERSONID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PERSONID),
FIRSTNAME VARCHAR(15),
LASTNAME VARCHAR(15),
AGE INT)";
105
MYSQL_QUERY($SQL,$CON);
PHP MYSQL INSERT INTO
• The INSERT INTO statement is used to insert new records in a table.
Insert Data Into a Database Table
• The INSERT INTO statement is used to add new records to a
database table.
SYNTAX
• It is possible to write the INSERT INTO statement in two forms.
• The first form doesn't specify the column names where the data will
be inserted, only their values:
INSERT INTO TABLE_NAME
VALUES (VALUE1, VALUE2, VALUE3,...)
• The second form specifies both the column names and the values to
be inserted:
INSERT INTO TABLE_NAME (COLUMN1, COLUMN2, COLUMN3,...)
VALUES (VALUE1, VALUE2, VALUE3,...)
• To get PHP to execute the statements above we must use the
mysql_query() function. This function is used to send a query or
command to a MySQL connection. 106
EXAMPLE
• In the previous lesson we created a table named "Persons", with three
columns; "Firstname", "Lastname" and "Age". We will use the same table in
this example. The following example adds two new records to the "Persons"
table:
< ?PHP
$CON = MYSQL_CONNECT("LOCALHOST","PETER","ABC123");
IF (!$CON)
{
DIE('COULD NOT CONNECT: ' . MYSQL_ERROR());
}

MYSQL_SELECT_DB("MY_DB", $CON);

MYSQL_QUERY("INSERT INTO PERSONS (FIRSTNAME, LASTNAME, AGE)


VALUES ('PETER', 'GRIFFIN',35)");

MYSQL_QUERY("INSERT INTO PERSONS (FIRSTNAME, LASTNAME, AGE)


VALUES ('GLENN', 'QUAGMIRE',33)");

MYSQL_CLOSE($CON);
107
?>
Insert Data From a Form Into a Database
• Now we will create an HTML form that can be used to add
new records to the "Persons" table.
• Here is the HTML form:
< HTML>
< BODY>

< FORM ACTION="INSERT.PHP" METHOD="POST">


FIRSTNAME: <INPUT TYPE="TEXT" NAME="FIRSTNAME" />
LASTNAME: <INPUT TYPE="TEXT" NAME="LASTNAME" />
AGE: <INPUT TYPE="TEXT" NAME="AGE" />
< INPUT TYPE="SUBMIT" />
< /FORM>

< /BODY>
< /HTML> 108
• When a user clicks the submit button in the HTML form in the example above, the form data is sent
to "insert.php".
• The "insert.php" file connects to a database, and retrieves the values from the form with the PHP
$_POST variables.
• Then, the mysql_query() function executes the INSERT INTO statement, and a new record will be
added to the "Persons" table.
• Here is the "insert.php" page:
< ?PHP
$CON = MYSQL_CONNECT("LOCALHOST","PETER","ABC123");
IF (!$CON)
{
DIE('COULD NOT CONNECT: ' . MYSQL_ERROR());
}

MYSQL_SELECT_DB("MY_DB", $CON);

$SQL="INSERT INTO PERSONS (FIRSTNAME, LASTNAME, AGE)


VALUES
('$_POST[FIRSTNAME]','$_POST[LASTNAME]','$_POST[AGE]')";

IF (!MYSQL_QUERY($SQL,$CON))
{
DIE('ERROR: ' . MYSQL_ERROR());
}
ELSE
ECHO "1 RECORD ADDED";

MYSQL_CLOSE($CON); 109
?>
PHP MYSQL SELECT
• The SELECT statement is used to select data
from a database.
Select Data From a Database Table
• The SELECT statement is used to select data
from a database.
SYNTAX
• SELECT COLUMN_NAME(S)
FROM TABLE_NAME
• To get PHP to execute the statement above we
must use the mysql_query() function. This
function is used to send a query or command
to a MySQL connection. 110
EXAMPLE
• The following example selects all the data stored in the "Persons" table (The * character
selects all the data in the table):
< ?PHP
$CON = MYSQL_CONNECT("LOCALHOST","PETER","ABC123");
IF (!$CON)
{
DIE('COULD NOT CONNECT: ' . MYSQL_ERROR());
}

MYSQL_SELECT_DB("MY_DB", $CON);

$RESULT = MYSQL_QUERY("SELECT * FROM PERSONS");

WHILE($ROW = MYSQL_FETCH_ARRAY($RESULT))
{
ECHO $ROW['FIRSTNAME'] . " " . $ROW['LASTNAME'];
ECHO "<BR />";
}

MYSQL_CLOSE($CON);
?>
• The example above stores the data returned by the mysql_query() function in the $result
variable.
• Next, we use the mysql_fetch_array() function to return the first row from the recordset as
an array. Each call to mysql_fetch_array() returns the next row in the recordset. The while
111
loop loops through all the records in the recordset. To print the value of each row, we use
Display the Result in an HTML Table
• The following example selects the same data as the example above, but will display the data in an HTML
table:
< ?PHP
$CON = MYSQL_CONNECT("LOCALHOST","PETER","ABC123");
IF (!$CON)
{
DIE('COULD NOT CONNECT: ' . MYSQL_ERROR());
}

MYSQL_SELECT_DB("MY_DB", $CON);

$RESULT = MYSQL_QUERY("SELECT * FROM PERSONS");

ECHO "<TABLE BORDER='1'>


<TR>
< TH>FIRSTNAME</TH>
< TH>LASTNAME</TH>
< /TR>";

WHILE($ROW = MYSQL_FETCH_ARRAY($RESULT))
{
ECHO "<TR>";
ECHO "<TD>" . $ROW['FIRSTNAME'] . "</TD>";
ECHO "<TD>" . $ROW['LASTNAME'] . "</TD>";
ECHO "</TR>";
}
ECHO "</TABLE>";

MYSQL_CLOSE($CON);
112
?>
PHP MYSQL THE WHERE CLAUSE
• The WHERE clause is used to filter records.
The WHERE clause
• The WHERE clause is used to extract only those records that fulfill a specified criterion.
SYNTAX
SELECT COLUMN_NAME(S)
FROM TABLE_NAME
WHERE COLUMN_NAME OPERATOR VALUE
• To get PHP to execute the statement above we must use the mysql_query() function. This function is used
to send a query or command to a MySQL connection.
EXAMPLE
• The following example selects all rows from the "Persons" table where "FirstName='Peter'":
< ?PHP
$CON = MYSQL_CONNECT("LOCALHOST","PETER","ABC123");
IF (!$CON)
{
DIE('COULD NOT CONNECT: ' . MYSQL_ERROR());
}

MYSQL_SELECT_DB("MY_DB", $CON);

$RESULT = MYSQL_QUERY("SELECT * FROM PERSONS


WHERE FIRSTNAME='PETER'");

WHILE($ROW = MYSQL_FETCH_ARRAY($RESULT))
{
ECHO $ROW['FIRSTNAME'] . " " . $ROW['LASTNAME'];
ECHO "<BR />";
}
113
?>
PHP MYSQL ORDER BY KEYWORD
• The ORDER BY keyword is used to sort the data in a
recordset.
The ORDER BY Keyword
• The ORDER BY keyword is used to sort the data in a
recordset.
• The ORDER BY keyword sort the records in
ascending order by default.
• If you want to sort the records in a descending
order, you can use the DESC keyword.
SYNTAX
• SELECT COLUMN_NAME(S)
FROM TABLE_NAME
ORDER BY COLUMN_NAME(S) ASC|DESC 114
EXAMPLE
• The following example selects all the data stored in the "Persons" table, and sorts
the result by the "Age" column:
< ?PHP
$CON = MYSQL_CONNECT("LOCALHOST","PETER","ABC123");
IF (!$CON)
{
DIE('COULD NOT CONNECT: ' . MYSQL_ERROR());
}

MYSQL_SELECT_DB("MY_DB", $CON);

$RESULT = MYSQL_QUERY("SELECT * FROM PERSONS ORDER BY AGE");

WHILE($ROW = MYSQL_FETCH_ARRAY($RESULT))
{
ECHO $ROW['FIRSTNAME'];
ECHO " " . $ROW['LASTNAME'];
ECHO " " . $ROW['AGE'];
ECHO "<BR />";
}

MYSQL_CLOSE($CON);
115
?>
Order by Two Columns
• It is also possible to order by more than one
column. When ordering by more than one
column, the second column is only used if
the values in the first column are equal:
• SELECT COLUMN_NAME(S)
FROM TABLE_NAME
ORDER BY COLUMN1, COLUMN2

116
PHP MYSQL UPDATE
• The UPDATE statement is used to modify data in a
table.
Update Data In a Database
• The UPDATE statement is used to update existing
records in a table.
SYNTAX
• UPDATE TABLE_NAME
SET COLUMN1=VALUE, COLUMN2=VALUE2,...
WHERE SOME_COLUMN=SOME_VALUE
• NOTE: THE WHERE CLAUSE SPECIFIES WHICH
RECORD OR RECORDS THAT SHOULD BE UPDATED.
IF YOU OMIT THE WHERE CLAUSE, ALL RECORDS
WILL BE UPDATED! 117
• The following example updates some data in the "Persons"
table:
< ?PHP
$CON =
MYSQL_CONNECT("LOCALHOST","PETER","ABC123");
IF (!$CON)
{
DIE('COULD NOT CONNECT: ' . MYSQL_ERROR());
}

MYSQL_SELECT_DB("MY_DB", $CON);

MYSQL_QUERY("UPDATE PERSONS SET AGE=36


WHERE FIRSTNAME='PETER' AND LASTNAME='GRIFFIN'");

MYSQL_CLOSE($CON);
?> 118
• To get PHP to execute the statement above
we must use the mysql_query() function.
This function is used to send a query or
command to a MySQL connection.
EXAMPLE
• Earlier in the tutorial we created a table
named "Persons". Here is how it looks:

FIRSTNAME LASTNAME AGE

PETER GRIFFIN 35

GLENN QUAGMIRE 33

119
PHP MYSQL DELETE
• The DELETE statement is used to delete records in a
table.
Delete Data In a Database
• The DELETE FROM statement is used to delete records
from a database table.
SYNTAX
DELETE FROM TABLE_NAME
WHERE SOME_COLUMN = SOME_VALUE
• NOTE: THE WHERE CLAUSE SPECIFIES WHICH RECORD
OR RECORDS THAT SHOULD BE DELETED. IF YOU OMIT
THE WHERE CLAUSE, ALL RECORDS WILL BE DELETED!
• To get PHP to execute the statement above we must
use the mysql_query() function. This function is used
to send a query or command to a MySQL connection. 120
EXAMPLE
• Look at the following "Persons" table:

FIRSTNAME LASTNAME AGE

PETER GRIFFIN 35

GLENN QUAGMIRE 33

• The following example deletes all the records in the "Persons" table where LastName='Griffin':
< ?PHP
$CON = MYSQL_CONNECT("LOCALHOST","PETER","ABC123");
IF (!$CON)
{
DIE('COULD NOT CONNECT: ' . MYSQL_ERROR());
}

MYSQL_SELECT_DB("MY_DB", $CON);

MYSQL_QUERY("DELETE FROM PERSONS WHERE LASTNAME='GRIFFIN'");

MYSQL_CLOSE($CON);
121
?>
Changing a Table definition (ALTER TABLE)
• The ALTER TABLE command is used to change the
structure/definition of an existing table.
It is used mainly to:
• Add a new column to a table
• Drop a column from a table
• Add a new table constraint
• Drop a table constraint
The basic format of the statement is:
• ALTER TABLE table_name [ADD|DROP [COLUMN] column_name
data_type [NOT NULL]]
• [ALTER [COLUMN] column_name data_type]
• [DROP [COLUMN] column_name]
• [ADD [CONSTRAINT [constraint_name]] table_constraint_definition]
• [DROP CONSTRAINT constraint_name [RESTRICT|CASCADE]]
Example
• ALTER TABLE table_name ADD email VARCHAR(60) AFTER name;
• If you want the new column to be first, use this statement:
ALTER TABLE table_name ADD email VARCHAR(60) FIRST; 122
Chapter Four
Cookies and Sessions
The stateless nature of HTTP
• Stateful and stateless are adjectives that describe whether a computer
or computer program is designed to note and remember one or more
preceding events in a given sequence of interactions with a user,
another computer or program, a device, or other outside element.
• Stateful means the computer or program keeps track of the state of
interaction, usually by setting values in a storage field designated for
that purpose.
• Stateless means there is no record of previous interactions and each
interaction request has to be handled based entirely on information
that comes with it.
• Stateful and stateless are derived from the usage of state as a set of
conditions at a moment in time. (Computers are inherently stateful in
operation, so these terms are used in the context of a particular set of
interactions, not of how computers work in general.)
123
• A fundamental characteristics of the web is the stateless interaction
b/n browsers and web servers
• Each HTTP request a browser sends to a web server is independent
of any other request
• The stateless nature of HTTP allows users to browse the Web by
following hypertext links and visiting pages in any order.
• HTTP also allows applications to distribute or even replicate
content across multiple servers to balance the load generated by a
high number of requests. These features are possible because of the
stateless nature of HTTP.
• HTTP is called a stateless protocol because each command is
executed independently, without any knowledge of the commands
that came before it.
• This is the main reason that it is difficult to implement Web sites
that react intelligently to user input.
• This shortcoming of HTTP is being addressed in a number of new
technologies, including ActiveX, Java, JavaScript and cookies 124
Cookies and Sessions
• Owing to the fact that HTTP is stateless - that is, any
data you have stored is forgotten about when the page
has been sent to the client and the connection is
closed - it took a little work to find a solution to the
problem.
• Eventually, Netscape put a solution into their browser
known as "cookies" - tiny bits of information that a
web site could store on the client's machine that were
sent back to the web site each time a new page was
requested.
• Each cookie could only be read by the web site that
had written it, meaning that it was a secure way to
store information across pages. 125
PHP COOKIES
What is a Cookie?
• Cookies are used to store the information of a web page in a remote browser, so
that when the same user comes back to that page, those information can be
retrieved from the browser itself.
Uses of cookie
Cookies are often used to perform following tasks:
• Session management: Cookies are widely used to manage user sessions. For
example, when you use an online shopping cart, you keep adding items in the cart
and finally when you checkout, all of those items are added in the list of items you
have purchased. This can be achieved using cookies.
• User identification: Once a user visits a webpage, using cookies, that user can be
remembered. And later on, depending upon the search/visit pattern of the user,
content which the user likely to be visited are served. A good example of this is
'Retargetting'. A concept used in online marketing, where depending upon the
user's choice of content, advertisements of relevant product, which the user may
buy, are served.
• Tracking / Analytics: Cookies are used to track the user. Which, in turn, is used to
analyze and serve various kind of data of great value, like location, technologies
(e.g. browser, OS) form where the user visited, how long (s)he stayed on various
pages etc. 126
• 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.
How to Create a Cookie?
• The setcookie() function is used to set a cookie.
• Note: The setcookie() function must appear BEFORE
the <html> tag.
SYNTAX
SETCOOKIE(NAME, VALUE, EXPIRE); OR

setcookie(name, value, expire, path, domain, secure,


httponly); 127
• setcookie() has several parameters. following
table discusses those.

128
• Example
• Following example shows how to create a cookie in PHP. Code first and then
some explanation.
<?php
$cookie_value = "w3resource tutorials";
setcookie("w3resource", $cookie_value, time()+3600, "/home/
your_usename/", "example.com", 1, 1);
if (isset($_COOKIE['cookie']))
echo $_COOKIE["w3resource"];
?>
• So, what does the code above does? The first parameter sets the name of the
cookie as 'w3resource', the second parameter sets the value as 'w3resource
tutorials', the third parameter states that the cookie will be expired after 3600
seconds (note the way it has been declared, we use time() and then add the
number of seconds we wish the cookie must be expired after), the fourth
parameter sets path on the server '/home/your_name' where your_name may be
an username, so it directs the home directory of a user, the fifth and sixth
parameter is set to 1, i.e. true, so the cookie is available over secure connections
only and it is available on HTTP protocol only.
• echo $_COOKIE["w3resource"]; simply prints the cookie value. This way you can
retrieve a cookie value.
Output 129
EXAMPLE 1
• In the example below, we will create a cookie
named "user" and assign the value "Alex" to it.
We also specify that the cookie should expire
after one hour:
< ?PHP
SETCOOKIE("USER", "ALEX", TIME()+3600);
?>

< HTML>
.....

130
EXAMPLE 2
• You can also set the expiration time of the cookie in
another way. It may be easier than using seconds.
<?PHP
$EXPIRE=TIME()+60*60*24*30;
SETCOOKIE("USER", "ALEX", $EXPIRE);
?>

< HTML>
.....
• In the example above the expiration time is set to a
month (60 sec * 60 min * 24 hours * 30 days).
131
How to Retrieve a Cookie Value?
• The PHP $_COOKIE variable is used to retrieve a cookie value.

In the example below, we retrieve the value of the cookie named "user" and display it on a page:
< ?PHP
// PRINT A COOKIE
ECHO $_COOKIE["USER"];

// A WAY TO VIEW ALL COOKIES


PRINT_R($_COOKIE);
?>
• In the following example we use the isset() function to find out if a cookie has been set:
< HTML>
< BODY>

< ?PHP
IF (ISSET($_COOKIE["USER"]))
ECHO "WELCOME " . $_COOKIE["USER"] . "!<BR />";
ELSE
ECHO "WELCOME GUEST!<BR />";
?>

< /BODY>
< /HTML>
132
<?php
$Month = 2592000 + time();
//this adds 30 days to the current time
setcookie(AboutVisit, date("F jS - g:i a"), $Month);
?>
• The above code sets a cookie in the visitor's browser called "AboutVisit". The
cookie sets the value to the current date, and set's the expiration to be be in 30
days (2592000 = 60 seconds * 60 mins * 24 hours * 30 days.)
• Now let's retrieve the cookie.
<?php
if(isset($_COOKIE['AboutVisit']))
{
$last = $_COOKIE['AboutVisit'];
echo "Welcome back! <br> You last visited on ". $last;
}
else
{
echo "Welcome to our site!";
}
?>
• This code first checks if the cookie exists. If it does, it welcomes the user back
133
and tells them when they last visited. If they are new, it skips this and prints a
How to Delete a Cookie?
• When deleting a cookie you should assure that
the expiration date is in the past.
• Delete example:
< ?PHP
// SET THE EXPIRATION DATE TO ONE HOUR
AGO
SETCOOKIE("USER", "", TIME()-3600);
?>

134
<html>
<head>
<title>Writing a cookie to the client computer</title>
</head>
<body style = "font-family: arial, sans-serif;
background-color: #99CCFF">
<h2>Write Cookie to save your cookie data.</h2>
<form method = "post" action = "cookies.php"
style = "font-size: 10pt"> Form data is posted to cookies.php.
<strong>Name:</strong><br />
<input type = "text" name = "NAME" /><br />
<strong>Height:</strong><br />
<input type = "text" name = "HEIGHT" /><br />
<strong>Favorite Color:</strong><br />
<input type = "text" name = "COLOR" /><br />
<input type = "submit" value = "Write Cookie"
style = "background-color: #F0E86C; color: navy;
font-weight: bold" /></p>
</form>
</body>
</html>
135
<?php
// Program to write a cookie to a client's machine
extract( $_POST );
// write each form field’s value to a cookie and set the cookie’s expiration date
setcookie( "Name", $NAME, time() + 60 * 60 * 24 * 5 );
setcookie( "Height", $HEIGHT, time() + 60 * 60 * 24 * 5 );
setcookie( "Color", $COLOR, time() + 60 * 60 * 24 * 5 );
?> Function setcookie takes the name of
<html> the cookie to be set as the first
<head> argument, followed by the value to be
<title>Cookie Saved</title> stored in the cookie. The optional third
</head> argument specifies the expiration date of
<body style = "font-family: arial, sans-serif"> the cookie.
<p>The cookie has been set with the following data:</p>
<!-- print each form field’s value --> Each form field’s value is printed to
<br /><span style = "color: blue">Name:</span> confirm the data that has been set as a
<?php print( $NAME ) ?><br /> cookie with the user.
<span style = "color: blue">Height:</span>
<?php print( $HEIGHT ) ?><br />
<span style = "color: blue">Favorite Color:</span>
<span style = "color: <?php print( "$COLOR\">$COLOR" ) ?>
</span><br />
Hyperlink to readCookies.php.
<p>Click <a href = "readCookies.php">here</a>
to read the saved cookie.</p>
136
</body>
<html>
PHP creates array $_COOKIE
<head><title>Read Cookies</title></head> which contains all cookie
<body style = "font-family: arial, sans-serif"> values indexed by their names.

<p><strong>
The following data is saved in a cookie on your computer.</strong>
</p><table border = "5" cellspacing = "0" cellpadding = "10">
<?php
foreach ( $_COOKIE as $key => $value )
The foreach loop iterates through the
print( "<tr> $_COOKIE array and prints the name and v
<td bgcolor=\"#F0E68C\">$key</td> of each cookie in an XHTML table.
<td bgcolor=\"#FFA500\">$value</td>
</tr>" );
?>
</table>
</body>
137
</html>
What if a Browser Does NOT Support Cookies?
• If your application deals with browsers that do not support cookies, you will have to use other
methods to pass information from one page to another in your application. One method is to
pass the data through forms.
• The form below passes the user input to "welcome.php" when the user clicks on the
"Submit" button:
< HTML>
< BODY>
< FORM ACTION="WELCOME.PHP" METHOD="POST">
NAME: <INPUT TYPE="TEXT" NAME="NAME" />
AGE: <INPUT TYPE="TEXT" NAME="AGE" />
< INPUT TYPE="SUBMIT" />
< /FORM>

< /BODY>
< /HTML>
• Retrieve the values in the "welcome.php" file like this:
< HTML>
< BODY>

WELCOME <?PHP ECHO $_POST["NAME"]; ?>.<BR />


YOU ARE <?PHP ECHO $_POST["AGE"]; ?> YEARS OLD.

< /BODY>
138
< /HTML>
PHP SESSIONS
• A PHP session variable is used to store information about, or change
settings for a user session.
• Session variables hold information about one single user, and are
available to all pages in one application.
PHP Session Variables
• When you are working with an application, you open it, do some changes
and then you close it. This is much like a Session. The computer knows
who you are. It knows when you start the application and when you end.
• But on the internet there is one problem: the web server does not know
who you are and what you do because the HTTP address doesn't maintain
state.
• A PHP session solves this problem by allowing you to store user
information on the server for later use (i.e. username, shopping items,
etc).
• However, session information is temporary and will be deleted after the
user has left the website. If you need a permanent storage you may want
to store the data in a database.
• Sessions work by creating a unique id (UID) for each visitor and store
variables based on this UID. The UID is either stored in a cookie or is
139
propagated in the URL.
Starting a PHP Session
• Before you can store user information in your PHP
session, you must first start up the session.
• Note: The session_start() function must appear
BEFORE the <html> tag:
< ?PHP SESSION_START(); ?>

< HTML>
< BODY>

< /BODY>
< /HTML>
• The code above will register the user's session with the
server, allow you to start saving user information, and
assign a UID for that user's session.
140
Storing a Session Variable
• The correct way to store and retrieve session variables is to use
the PHP $_SESSION variable:
< ?PHP
SESSION_START();
// STORE SESSION DATA
$_SESSION['VIEWS']=1;
?>

< HTML>
< BODY>

< ?PHP
//RETRIEVE SESSION DATA
ECHO "PAGEVIEWS=". $_SESSION['VIEWS'];
?>

< /BODY>
< /HTML> 141
• In the example below, we create a simple page-
views counter. The isset() function checks if the
"views" variable has already been set. If "views"
has been set, we can increment our counter. If
"views" doesn't exist, we create a "views" variable,
and set it to 1:
<?PHP
SESSION_START();

IF(ISSET($_SESSION['VIEWS']))
$_SESSION['VIEWS']=$_SESSION['VIEWS']+1;
ELSE
$_SESSION['VIEWS']=1;
ECHO "VIEWS=". $_SESSION['VIEWS'];
?> 142
Destroying a Session
• If you wish to delete some session data, you can use the
unset() or the session_destroy() function.
• The unset() function is used to free the specified session
variable:
< ?PHP
SESSION_START();
IF(ISSET($_SESSION['VIEWS']))
UNSET($_SESSION['VIEWS']);
?>
• You can also completely destroy the session by calling the
session_destroy() function:
< ?PHP
SESSION_DESTROY();
?>
• Note: session_destroy() will reset your session and you will
lose all your stored session data. 143
What’s the difference between a cookie and a session in
PHP?
• PHP sessions improve upon cookies because they allow
web applications to store and retrieve more information
than cookies. PHP sessions actually use cookies, but they
add more functionality and security.
1. Sessions store data on the server, not on the browser
like cookies
• The main difference between a session and a cookie is
that session data is stored on the server, whereas cookies
store data in the visitor’s browser. Sessions use a session
identifier to locate a particular user’s session data. This
session identifier is normally stored in the user’s web
browser in a cookie, but the sensitive data that needs to
be more secure — like the user’s ID, name, etc. — will
always stay on the server. 144
2. Sessions are more secure than cookies
• So, why exactly should we use sessions when cookies work just fine? Well, as
we already mentioned, sessions are more secure because the relevant
information is stored on the server and not sent back and forth between the
client and server. The second reason is that some users either turn off cookies
or reject them. In that scenario, sessions, while designed to work with a
cookie, can actually work without cookies as a workaround, as you can read
about here:
3. Sessions need extra space, unlike cookies
• PHP sessions, unlike cookies which are just stored on the user’s browser, need
a temporary directory on the server where PHP can store the session data.
For servers running Unix this isn’t a problem at all, because the /tmp
directory is meant to be used for things like this. But, if your server is running
Windows and a version of PHP earlier than 4.3.6, then the server will need to
be configured – here is what to do: Create a new folder on your Windows
server – you can call it something like C:\temp. You want to be sure that every
user can read and write to this folder. Then, you will need to edit your php.ini
file, and set the value of session.save_path to point to the folder which you
created on the Windows server (in this case, that folder is under C:\temp).
And finally, you will need to restart your web server so that the changes in
the php.ini file take effect. 145
• The other difference between sessions and cookies is that
a session can hold multiple variables, and you don’t have
to set cookies for every variable.
• By default, the session data is stored in a cookie with an
expiry date of zero, which means that the session only
remains active as long as the browser.
• When you close the browser, all the stored information is
lost.
• You can modify this behavior by changing the
“session.cookie_lifetime” setting in “php.ini” from zero to
whatever you want the cookie lifetime to be.
• If you want sessions to start automatically, you must
enable the “session.auto_start” setting in PHP’s
configuration file. This way a session will be initiated for
every PHP document. 146
• Here’s another example, this one asking you to log in and then
storing your login name and
session start time as two session variables.
• This information is then used to display the
total number of minutes the session has been active.
<?php
// initialize a session
session_start();
?>
<html>
<head></head>
<body>
<?php
if (!isset($_SESSION['name']) && !isset($_POST['name'])) {
// if no data, print the form
?> 147
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="text" name="name">
<input type="submit" name="submit" value="Enter your name">
</form>
<?php
}
else if (!isset($_SESSION['name']) && isset($_POST['name'])) {
// if a session does not exist but the form has been submitted
// check to see if the form has all required values
// create a new session
if (!empty($_POST['name'])) {
$_SESSION['name'] = $_POST['name'];
$_SESSION['start'] = time();
echo "Welcome, " . $_POST['name'] . ". A new session has been
activated for you. Click <a href=" . $_SERVER['PHP_SELF'] . ">here</a> to
refresh the page.";
} 148
else {
echo "ERROR: Please enter your name!";
}
}
else if (isset($_SESSION['name'])) {
// if a previous session exists
// calculate elapsed time since session start and now
echo "Welcome back, " . $_SESSION['name'] . ". This session
was activated " . round((time() - $_SESSION['start']) / 60) . "
minute(s) ago. Click <a href=" . $_SERVER['PHP_SELF'] .
">here</a> to refresh the page.";
}
?>
</body>
</html> 149

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy