Download as pdf or txt
Download as pdf or txt
You are on page 1of 107

1

Chapter 26 - PHP
Outline
26.1 Introduction
26.2 PHP
26.3 String Processing and Regular Expressions
26.4 Viewing Client/Server Environment Variables
26.5 Form Processing and Business Logic
26.6 Verifying a Username and Password
26.7 Connecting to a Database
26.8 Cookies
26.9 Dynamic Content in PHP
26.10 Operator Precedence
26.11 Web Resources

 2003 Prentice Hall, Inc. All rights reserved.


2

Objectives

In this chapter, you will learn:


– To understand PHP data types, operators, arrays and control
structures.
– To understand string processing and regular expressions in
PHP.
– To construct programs that process form data.
– To be able to read and write client data using cookies.
– To construct programs that interact with MySQL databases.

 2003 Prentice Hall, Inc. All rights reserved.


3

26.1 Introduction

• PHP
– PHP: Hypertext Preprocessor
– Originally called “Personal Home Page Tools”
– Popular server-side scripting technology
– Open-source
• Anyone may view, modify and redistribute source code
• Supported freely by community
– Platform independent

 2003 Prentice Hall, Inc. All rights reserved.


4

26.2 PHP

• Basic application
– Scripting delimiters
• <? php ?>
• Must enclose all script code
– Variables preceded by $ symbol
• Case-sensitive
– End statements with semicolon
– Comments
• // for single line
• /* */ for multiline
– Filenames end with .php by convention

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
5
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
strict.dtd">
Outline
3
4 <!--
<!-- Fig. 26.1: first.php -->
-->
5 <!--
<!-- Our first PHP script -->
--> first.php
6 Scripting delimiters (1 of 1)
7 <?php
8 $name = "LunaTic";
"LunaTic"; // declaration
9 ?> Declare variable $name
10
11 <html xmlns = "http://www.w3.org/1999/xhtml">
"http://www.w3.org/1999/xhtml">
12 <head>
13 <title>A
<title>A simple PHP document </title>Single-line
document</title> comment
14 </head>
15
16 <body style
style = "font-
"font-size: 2em">
2em">
17 <p>
18 <strong>
19
20 <!--
<!-- print variable name’s value -->
-->
21 Welcome to PHP, <?php print(
print( "$name" ); ?>!
?>!
22 </strong>
23 </p>
24 </body>
Function print outputs the value of variable
$name
25 </html>
</html>

 2003 Prentice Hall, Inc.


All rights reserved.
6

26.2 PHP
Fig. 26.1 Simple PHP program.

 2003 Prentice Hall, Inc. All rights reserved.


7

26.2 PHP

• Variables
– Can have different types at different times
– Variable names inside strings replaced by their value
– Type conversions
• settype function
• Type casting
– Concatenation operator
• . (period)
• Combine strings

 2003 Prentice Hall, Inc. All rights reserved.


8

26.2 PHP

Data type Description


int, integer Whole numbers (i.e., numbers without a decimal point).
float, double Real numbers (i.e., numbers containing a decimal point).
string Text enclosed in either single ('') or double ("") quotes.
bool, Boolean True or false.
array Group of elements of the same type.
object Group of associated data and methods.
Resource An external data source.
NULL No value.
Fig. 26.2 PHP data types.

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
9
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd"> Outline
3
4 <!--
<!-- Fig. 26.3: data.php -->
-->
5 <!--
<!-- Demonstration of PHP data types -->
--> data.php
6 (1 of 3)
7 <html xmlns = "http://www.w3.org/1999/xhtml">
"http://www.w3.org/1999/xhtml">
8 <head>
9 <title>PHP
<title>PHP data types</title>
types</title>
10 </head>
11
12 <body>
13
14 <?php Assign a string to variable
15 $testString
16 // declare a string, double and integer
17 $testString = "3.5
"3.5 seconds";
seconds";
18 $testDouble = 79.2;
79.2;
Assign a double to variable
Assign an integer to variable
$testDouble
19 $testInteger = 12;
12;
$testInteger
20 ?>
21

 2003 Prentice Hall, Inc.


All rights reserved.
22 <!--
<!-- print each variable’s value -->
-->
10
23 <?php print(
print( $testString ); ?> is a string.<br
string.<br />
Outline
24 <?php print(
print( $testDouble ); ?> is a double.<br
double.<br />
25 <?php print(
print( $testInteger ); ?> is an integer.<br
integer.<br />
26 data.php
27 <br /> Print each variable’s (2 of 3)
value
28 Now, converting to other types:<br
types:<br />
29 <?php
30
31 // call function settype to convert variable
32 // testString to different data types
33 print(
print( "$testString" );
34 settype( $testString, "double" );
35 print(
print( " as a double is $testString <br />" );
36 print(
print( "$testString" );
37 settype( $testString, "integer" );
38 print(
print( " as an integer is $testString <br />" );
39 settype( $testString, "string" );
40 print( "Converting back toCall
print( function
a string settype
results in to
41 $testString <br /><br convert
/>" the data type
); settype
Call function to of
42 convertvariable
the data$testString
type of to a
43 $data = "98.6 degrees";
degrees"; double.
variable $testString to an
integer.
Convert variable $testString
back to a string

 2003 Prentice Hall, Inc.


All rights reserved.
44
11
45 // use type casting to cast variables to a
Outline
46 // different type
47 print(
print( "Now using type casting instead: <br />
48 As a string - " . (string
(string)
string) $data . data.php
49 "<br />As a double - " . (double
(double)
double) $data . (3 of 3)
50 "<br />As an integer - " . (integer
(integer)
integer) $data );
51 ?>
Use type casting to cast variable
52 </body>
$data to different types
53 </html>

 2003 Prentice Hall, Inc.


All rights reserved.
12

26.2 PHP
Fig. 26.3 Type conversion.

 2003 Prentice Hall, Inc. All rights reserved.


13

26.2 PHP

• Arithmetic operators
– Assignment operators
• Syntactical shortcuts
• Before being assigned values, variables have value undef
• Constants
– Named values
– define function

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
14
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd"> Outline
3
4 <!--
<!-- Fig. 26.4: operators.php -->
-->
5 <!--
<!-- Demonstration of operators -->
--> operators.php
6 (1 of 3)
7 <html xmlns = "http://www.w3.org/1999/xhtml"
"http://www.w3.org/1999/xhtml">
ttp://www.w3.org/1999/xhtml">
8 <head>
9 <title>Using
<title>Using arithmetic opera
operators
rators</title>
tors</title>
10 </head>
11
12 <body>
13 <?php
14 $a = 5; Define constant VALUE.
15 print(
print( "The value of variable a is $a <br />" );
16
17 // define constant VALUE
Add constant VALUE to variable $a.
18 define( "VALUE",
"VALUE", 5 );
19
20 // add constant VALUE to variable $a
21 $a = $a + VALUE;
VALUE;
22 print(
print( "Variable a after adding constant VALUE
23 is $a <br />" );
24

 2003 Prentice Hall, Inc.


All rights reserved.
25 // multiply variable $a by 2
15
26 $a *= 2;
Multiply variable $a by two using the Outline
27 print(
print( "Multiplying variable a by 2 yields $a <br />" );
multiplication assignment operator *=.
28
29 // test if variable $a is less than 50 operators.php
30 if ( $a < 50 )
Print if variable $a isTest
lesswhether
than 50.variable $a is less(2than 50
of 3)
31 print
print(
int( "Variable a is less than 50 <br />" );
32
33 // add 40 to variable $a
Add 40 to variable $a using the addition assignment
34 $a += 40;
40;
operator +=.
35 print(
print( "Variable a after adding 40 is $a <br />" );
36
37 // test if variable $a is 50 or less
38 if ( $a < 51 )
39 print(
print( "Variable a is still 50 or less<br />" );
40
41 // test if variable $a is between 50 and 100, inclusive
42 elseif ( $a < 101 )
43 print(
print( "Variable a is now between 50 and 100,
44 inclusive<br />" );
45 else
46 print(
print( "Variable a is now greater than 100
47 <br />" );
48

 2003 Prentice Hall, Inc.


All rights reserved.
49 // print an uninitialized variable
16
print(
print( "Using a variable before initializing:
50
Outline
51 $nothing <br />" );
52
53 // add constant VALUE to an uninitialized variable operators.php
54 $test = $num + VALUE
VALUE; (3 of 3)
55 print(
print( "An uninitialized variable plus constant
56 VALUE yields $test <br />" );
57 Print anAdd
uninitialized variable
constant VALUE to (an
$nothing ).
uninitialized
58 // add a string to an integer
variable.
59 $str = "3 dollars";
dollars";
60 $a += $str;
61 print
print( "Adding a string to variable a yields $a
62 <br />" );
63 ?>
64 </body>
Add a string to an integer.
65 </html>

 2003 Prentice Hall, Inc.


All rights reserved.
17

26.2 PHP
Fig. 26.4 Using PHP’s arithmetic operators.

 2003 Prentice Hall, Inc. All rights reserved.


18

26.2 PHP

• Keywords
– Reserved for language features
– if…elseif…else
• Arrays
– Group of related data
• Elements
– Name plus braces and index
• Indices start at zero
– count function
– array function

 2003 Prentice Hall, Inc. All rights reserved.


19

26.2 PHP

• Arrays, cont.
– Built-in iterators
• Maintain pointer to element currently referenced
• reset
• key
• next
• foreach loops

 2003 Prentice Hall, Inc. All rights reserved.


20

26.2 PHP

PHP keywords
and do for include require true
break else foreach list return var
case elseif function new static virtual
class extends global not switch xor
continue false if or this while
default
Fig. 26.5 PHP keywords.

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
21
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd"> Outline
3
4 <!--
<!-- Fig. 26.6: arrays.php -->
-->
5 <!--
<!-- Array manipulation -->
--> arrays.php
6 (1 of 3)
7 <html xmlns = "http://www.w3.org/1999/xhtml"
"http://www.w3.org/1999/xhtml">
w3.org/1999/xhtml">
8 <head>
9 <title>Array
<title>Array manipulation</title>
manipulation</title>
10 </head>
11
12 <body>
13 <?php Create the array $first by assigning a value
14 to an array element.
15 // create array first
16 print(
print( "<strong>Creating the first array</strong>
17 <br />" );
18 $first[ 0 ] = "zero";
"zero";
19 $first[ 1 ] = Assign
"one";
"one"; a value to the array, omitting the index.
20 $first[ 2 ] = Appends
"two";
"two"; a Use
newaelement
for loop
to to
theprint
end out each
of the element’s index and value.
array.
21 $first[] = "three";
"three"; Function count returns the total number of elements in the
22 array.
23 // print each element’s index and value
24 for ( $i = 0; $i < count(
count( $first );
); $i++ )
25 print(
print( "Element $i is $first[$i] <br />" );

 2003 Prentice Hall, Inc.


All rights reserved.
26
22
27 print(
print( "<br /><strong>Creating the second array
Outline
Call function array to create an array that contains
28 </strong><br />" );
29 the arguments passed to it. Store the array in variable
30 // call function second .
array to create array$second arrays.php
31 $second = array( "zero",
"zero", "one",
"one", "two",
"two", "three" ); (2 of 3)
32 for ( $i = 0; $i < count( $second ); $i++ )
33 print(
print( "Element $i is $second[$i] <br />" );
34
35 print(
print( "<br /><strong>Creating the third array
36 </strong><br />" );
37
38 // assign values
values to non-
non-numerical indices
39 $third[ "ArtTic" ] = 21;
21;
Assign values to non-numerical indices
40 $third[ "LunaTic" ] = 18;
18;
in array $third.
41 $third[ "GalAnt" ] = 23;
23;
Function reset sets the internal pointer to the
42
first element of the array.
43 // iterate through the array elements and print each
44 // element’s name
name and value
45 for ( reset( $third ); $element = key( $third );
46 next( $third ) )
47 print(
print( "$element is $third[$element] <br />" );
48 Function key returns the index of the element which
the internal pointer references.
Function next moves the internal pointer to the next
element.
 2003 Prentice Hall, Inc.
All rights reserved.
49 print(
print( "<br /><strong>Creating the fourth array
23
50 </strong><br />" );
Outline
51
52 // call function array to create array fourth using
53 // string indices arrays.php
54 $fourth = array( (3 of 3)
55 "January" => "first",
"first", "February" => "second",
"second",
56 "March" => "third",
"third", "April" => "fourth",
"fourth",
57 "May" => "fifth", Operator
"fifth", "June" =>=> is "sixth",
used in,function array to assign each
"sixth"
58 "July" => "seventh",element
"seventh", "August"a string index. The
=> "eighth",
"eighth", value to the left of the
59 "September" => "ninth", operator
"ninth", is the
"October" => array index,
"tenth",
"tenth", and the value to the right is
60 "November" => "eleventh"the
"eleventh", element’s=>value.
,"December" "twelfth"
61 );
62
63 // print each element’s name and value
64 foreach ( $fourth as $element
$element => $value )
65 print(
print( "$element is the $value month <br />" );
66 ?>
67 </body>
68 </html>

 2003 Prentice Hall, Inc.


All rights reserved.
24

26.2 PHP
Fig. 26.6 Array manipulation.

 2003 Prentice Hall, Inc. All rights reserved.


25
26.3 String Processing and Regular
Expressions
• String processing
– Equality and comparison two important operations
– strcmp function
• Returns –1 if string 1 < string 2
• Returns 0 if string 1 = string 2
• Returns 1 if string 1 > string 2
– Relational operators

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
26
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd"> Outline
3
4 <!--
<!-- Fig. 26.7: compare.php -->
-->
5 <!--
<!-- String Comparison -->
--> compare.php
6 (1 of 2)
7 <html xmlns = "http://www.w3.org/1999/xhtml"
"http://www.w3.org/1999/xhtml">
w.w3.org/1999/xhtml">
8 <head>
9 <title>String
<title>String Comparison</title>
Comparison</title>
10 </head>
11
12 <body>
13 <?php
Use a for loop to iterate through each array element.
14
15 // create array fruits
16 $fruits = array( "apple",
"apple", "orange",
"orange", "banana" );
Function strcmp compares two strings. If the first string
17
alphabetically precedes the second, then –1 is returned. If
18 // iterate through each array element
19 for ( $i = 0; $i <
the strings are equal, 0 is returned. If the first string
count( $fruits ); $i++ ) {
20
alphabetically follows the second, then 1 is returned.
21 // call function strcmp to compare the array element
22 // to string "banana"
23 if ( strcmp( $fruits[ $i ], "banana" ) < 0 )
24 print(
print( $fruits[ $i ]."
]." is less than banana " );

 2003 Prentice Hall, Inc.


All rights reserved.
25 elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 )
27
26 print(
print( $fruits[ $i ].
Outline
27 " is greater than banana " );
28 else
29 print( ]." is Use
print( $fruits[ $i ]." relational
equal to bananaoperators
" ); to compare each array
compare.php
30
element to string “apple”. (2 of 2)
31 // use relational operators to compare each element
32 // to string "apple"
33 if ( $fruits[ $i ] < "apple" )
34 print(
print( "and less than apple! <br />" );
35 elseif ( $fruits[ $i ] > "apple" )
36 print(
print( "and greater than apple! <br />" );
37 elseif ( $fruits[ $i ] == "apple" )
38 print(
print( "and equal to apple! <br />" );
39
40 }
41 ?>
42 </body>
43 </html>

 2003 Prentice Hall, Inc.


All rights reserved.
28
26.3 String Processing and Regular
Expressions
Fig. 26.7 Using the string comparison operators.

 2003 Prentice Hall, Inc. All rights reserved.


29
26.3 String Processing and Regular
Expressions
• Regular expressions
– Pattern matching templates
– ereg function
• POSIX
– preg_match function
• Perl
– ereg_replace function
• Building regular expressions
– Metacharacters
• $, ., ^
– Brackets [ ]

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
30
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd"> Outline
3
4 <!--
<!-- Fig. 26.8: expression.php -->
-->
5 <!--
<!-- Using regular expressions -->
--> expression.php
6 (1 of 3)
7 <html xmlns = "http://www.w3.org/1999/xhtml"
"http://www.w3.org/1999/xhtml">
p://www.w3.org/1999/xhtml">
8 <head>
9 <title>Regular
<title>Regular expressions</title>
expressions</title>
10 </head>
11
12 <body>
13 <?php Function ereg searches for the literal
14 $search = "Now is the characters
time";
time"; Now inside variable $search.
15 print(
print( "Test string is: '$search'<br /><br />" );
);
16
17 // call function ereg to search for pattern 'Now'
18 // in variable search
19 if ( ereg( "Now",
"Now", $search ) )
20 print(
print( "String 'Now' was found.<br />" );
21

 2003 Prentice Hall, Inc.


All rights reserved.
22 // search for pattern 'Now' in the beginning of
31
23 // the string
Outline
24 if ( ereg( "^Now",
"^Now", $search ) )
The dollar sign special character ($) search for the
25 print(
print( "String 'Now' found at beginning
pattern
The caret special Now at
character (^)the end of the
matches the string.
26 of the line.<br />" ); expression.php
27 beginning of a string. Function ereg searches the (2 of 3)
28 // beginning of the string for pattern
search for pattern 'Now' at the end of the string Now .
29 if ( ereg( "Now$",
"Now$", $search ) )
30 print(
print( "String 'Now' was found at the end
31 of the line.<br />" );
32
33 // search for any word ending in 'ow'
34 if ( ereg( "[[:<:]]([a-
"[[:<:]]([a-zA-
zA-Z]*ow)[[:>:]]",
Z]*ow)[[:>:]]", $search,
35 $match ) )
36 print(
print( "Word found ending in 'ow': " .
37 $match[
$match[ 1 ] . "<br />" );
38
The expression
The specialinside the expressions
bracket parentheses,[[:<:]] and ,
[a-zA-Z]*ow
39 // search for any words beginning with 't'
matches
Placingany
[[:>:]] word
a pattern ending
matchin the in ow. The
parentheses
beginning quantifier
stores
and the of
end matched
*
a
40 print(
print( "Words beginning with 't' found: ");
");
matches
string thethe
in
word, preceding
array that
respectively. pattern 0 or more
is specified times.
in the third argument
41
42
to function ereg.
while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]",
"[[:<:]](t[[:alpha:]]+)[[:>:]]",
43 $search, $match
$match ) ) {
44 print(
print( $match[ 1 ] . " " );
The pattern used in this example,
45
[[:<:]](t[[:alpha:]]+)[[:>:]], matches any
The while word
loop is used to find
beginning witheach occurrence of a
the character
Function eregi is used to specify case insensitivet followed by one or
word in themore
stringcharacters.
beginningCharacter
with t. class [[:alpha:]]
pattern matches.
recognizes any alphabetic character.  2003 Prentice Hall, Inc.
All rights reserved.
46 // remove the first occurrence of a word beginning
32
47 // with 't' to find other instances in the string
Outline
48 $search = ereg_replace( $match[ 1 ], "",
"", $search );
49 }
50 expression.php
After printing a match of a word beginning with t, function
51 print(
print( "<br
"<br />" ); ereg_replace is called to remove the word from the (3 of 3)
string.
52 ?>
This is necessary be because to find multiple instances of a
53 </body>
given pattern, the first matched instance must first be removed.
54 </html>
Function ereg_replace takes three arguments: the pattern to
match, a string to replace the matched string and the string to
search.

 2003 Prentice Hall, Inc.


All rights reserved.
33
26.3 String Processing and Regular
Expressions
Fig. 26.8 Regular expressions in PHP.

 2003 Prentice Hall, Inc. All rights reserved.


34
26.3 String Processing and Regular
Expressions

Quantifier Matches
{n} Exactly n times.
{m,n} Between m and n times inclusive.
{n,} n or more times.
+ One or more times (same as {1,}).
* Zero or more times (same as {0,}).
? Zero or one time (same as {0,1}).
Fig. 26.9 Some PHP quantifiers.

 2003 Prentice Hall, Inc. All rights reserved.


35
26.3 String Processing and Regular
Expressions

Character class Description


alnum Alphanumeric characters (i.e., letters [a-zA-Z] or digits [0-9]).
alpha Word characters (i.e., letters [a-zA-Z]).
digit Digits.
space Whitespace.
lower Lowercase letters.
upper Uppercase letters.
Fig. 26.10 Some PHP character classes.

 2003 Prentice Hall, Inc. All rights reserved.


36
26.4 Viewing Client/Server Environment
Variables
• Environment variables
– Provide information about execution environment
• Type of Web browser
• Type of server
• Details of HTTP connection
– Stored as array in PHP
• $_ENV

 2003 Prentice Hall, Inc. All rights reserved.


37
26.4 Viewing Client/Server Environment
Variables
Variable name Description
$_SERVER Data about the currently running server.
$_ENV Data about the client’s environment.
$_GET Data posted to the server by the get method.
$_POST Data posted to the server by the post method.
$_COOKIE Data contained in cookies on the client’s computer.
$GLOBALS Array containing all global variables.
Fig. 26.11 Some useful global arrays.

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
38
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd"> Outline
3
4 <!--
<!-- Fig. 26.11: env.php -->
-->
5 <!--
<!-- Program to display environment variables -->
--> env.php
6 (1 of 1)
7 <html xmlns = "http://www.w3.org/1999/xhtml">
"http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Environment
<title>Environment Variables</title>
Variables</title>
10 </head>
11
12 <body>
13 <table border = "0" cellpadding = "2" cellspacing = "0"
14 width = "100%"
"100%">
00%">
15 <?php
16
17 // print the key and value for each element
18 // in the $_ENV array
19 foreach ( $_ENV as $key => $value )
20 print(
print( "<tr><td bgcolor = \"#11bbff\
"#11bbff\">
21 The foreach loop
<strong>$key</strong></td> is used to print out the keys and
22 values for each
<td>$value</td></tr>" ); element in the $_ENV array.
23 ?> PHP stores environment variables and their values in
24 </table> the $_ENV array.
25 </body>
26 </html>

 2003 Prentice Hall, Inc.


All rights reserved.
39
26.4 Viewing Client/Server Environment
Variables
Fig. 26.12 Displaying environment variables.

 2003 Prentice Hall, Inc. All rights reserved.


40

26.5 Form Processing and Business Logic

• Form processing
– action property
• Where to send form data
– method property
• post
– Each element has unique name

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
41
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd"> Outline
3
4 <!--
<!-- Fig. 26.13: form.html -->
-->
5 <!--
<!-- Form for use with the form.php program -->
--> form.html
6 (1 of 4)
7 <html xmlns = "http://www.w3.org/1999/xhtml">
"http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Sample
<title>Sample form to take user input in XHTML</title>
XHTML</title>
10 </head>
11
12 <body>
13 The action attribute of the form element
14 <h1>This
<h1>This is indicates
a sample registration that when the user clicks Register, the
form.</h1>
form.</h1>
15 Please fill form
in all fields and data
click will be posted to form.php.
Register.
16
17 <!--
<!-- post form data to form.php -->
-->
18 <form method = "post" action = "form.php">
"form.php">
19 <img src = "images/user.gif" alt = "User" /><br />
20 <span style = "color: blue">
blue">
21 Please fill out the fields below.<br
below.<br />
22 </span>
23

 2003 Prentice Hall, Inc.


All rights reserved.
24 <!--
<!-- create four text boxes for user input -->
-->
42
25
A unique name (e.g., email) is assigned to each Outline
<img src = "images/fname.gif" alt = "First Name" />
26 <input type = "text" name = "fname" /><br />
of the form’s input fields. When Register is
27
clicked, each field’s name and value are sent to
28 <img src = "images/lname.gif" alt = "Last
"Last Name" />
the Web server. form.html
29 <input type = "text" name = "lname" /><br /> (2 of 4)
30
31 <img src = "images/email.gif" alt = "Email" />
32 <input type = "text" name = "email" /><br />
33
34 <img src = "images/phone.gif"
"images/phone.gif" alt = "Phone" />
35 <input type = "text" name = "phone" /><br />
36
37 <span style = "font-
"font-size: 10pt">
10pt">
38 Must be in the form (555)555-
(555)555-5555</span>
5555</span>
39 <br /><br />
40
41 <img src = "images/downloads.gif"
42 alt = "Publications" /><br />
43
44 <span style = "color: blue">
blue">
45 Which book would you like information about?
46 </span><br />
47

 2003 Prentice Hall, Inc.


All rights reserved.
48 <!--
<!-- create drop-
drop-down list containing book names -->
-->
43
49 <select name = "book">
"book">
Outline
50 <option>Internet
<option>Internet and WWW How to Program 3e</option>
3e</option>
51 <option>C++
<option>C++ How to Program 4e</option>
4e</option>
52 <option>
<option>Java
n>Java How to Program 5e</option>
5e</option> form.html
53 <option>XML
<option>XML How to Program 1e</option>
1e</option> (3 of 4)
54 </select>
55 <br /><br />
56
57 <img src = "images/os.gif" alt = "Operating System" />
58 <br /><span style = "color: blue">
blue">
59 Which operating system are you currently using?
60 <br /></span>
61
62 <!--
<!-- create five radio buttons -->
-->
63 <input type = "radio" name = "os" value = "Windows XP"
64 checked = "checked" />
65 Windows XP
66
67 <input type = "radio" name = "os" value =
68 "Windows 2000" />
69 Windows 2000
70
71 <input type
type = "radio" name = "os" value =
72 "Windows 98" />
73 Windows 98<br
98<br />

 2003 Prentice Hall, Inc.


All rights reserved.
74
44
75 <input type = "radio" name = "os" value = "Linux" />
Outline
76 Linux
77
78 <input type = "radio" name = "os" value = "Other" /> form.html
79 Other<br
Other<br /> (4 of 4)
80
81 <!--
<!-- create a submit
submit button -->
-->
82 <input type = "submit" value = "Register" />
83 </form>
84
85 </body>
86 </html>

 2003 Prentice Hall, Inc.


All rights reserved.
45

26.5 Form Processing and Business Logic


Fig. 26.13 XHTML form for gathering user input.

 2003 Prentice Hall, Inc. All rights reserved.


46

26.5 Form Processing and Business Logic

• Business logic
– Confirm that valid information was entered
– extract function
• Creates variables corresponding to each key-value pair in array
• Easily retrieve all values sent to PHP page
– Regular expressions very helpful
– Do checks on client side where possible
• JavaScript
• Conserves server resources
• Ending a script
– die function
• Remember to close all HTML tags

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
47
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd"> Outline
3
4 <!--
<!-- Fig. 26.14: form.php -->
-->
5 <!--
<!-- Read information sent from form.html -->
--> form.php
6 (1 of 4)
7 <html xmlns = "http://www.w3.org/1999/xhtml">
"http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Form
<title>Form Validation</title>
Validation</title>
10 </head>
11
12 <body style = "font-
"font-family: arial,sans-
arial,sans-serif">
serif">
Function ereg is called to determine whether the
13 The parentheses in the expression must be
<?php phone number entered by the user is valid.
14 followed by The
threeexpression
digits ([0-9]{3} ), a closing
\( matches the opening
15 extract( $_POST );
parenthesis, parentheses
three digits, of
a literal hyphen and
a phone number.
16 four additional digits.
17 // determine whether phone number is valid and print
18 // an error message if not
19 if ( !ereg( "^\
"^\([0-
([0-9]{3}\
9]{3}\)[0-
)[0-9]{3}-
9]{3}-[0-
[0-9]{4}$",
9]{4}$",
20 $phone ) ){
21
We access the phone field’s value from
form.html by using variable $phone.

 2003 Prentice Hall, Inc.


All rights reserved.
22 print(
print( "<p><span style = \"color: red;
48
23 font-
font-size: 2em\
2em\">
Outline
24 INVALID PHONE NUMBER</span><br />
25 A valid phone number must be in the form
26 <strong>(555)555-
<strong>(555)555-5555</strong><br
5555</strong><br /> form.php
27 <span style = \"color: blue\
blue\"> (2 of 4)
28 Click the Back button, enter a valid phone
Function die terminates script execution
29 number and resubmit.<br /><br />
30 Thank You.</span></p></body></html>" );
31
32 die(); // terminate script execution
33 }
34 ?>
35
36 <p>Hi
<p>Hi
37 <span style = "color: blue">
blue">
38 <strong>
39 <?php print(
print( "$fname" ); ?>
40 </strong>
</strong>
41 </span>.
</span>.
42 Thank you for completing the survey.<br
survey.<br />
43

 2003 Prentice Hall, Inc.


All rights reserved.
44 You have been added to the
49
45 <span style = "color: blue">
blue">
Outline
46 <strong>
47 <?php print(
print( "$book " ); ?>
48 </strong> form.php
49 </span> (3 of 4)
50 mailing list.
51 </p>
</p>
52 <strong>The
<strong>The following information has been saved
53 in our database:</strong><br
database:</strong><br />
54
55 <table border = "0" cellpadding = "0" cellspacing = "10">
"10">
56 <tr>
57 <td bgcolor = "#ffffaa">
"#ffffaa">Name </td>
58 <td bgcolor = "#ffffbb">
"#ffffbb">Email</td>
Email</td>
59 <td bgcolor = "#ffffcc">
"#ffffcc">Phone</td>
Phone</td>
60 <td bgcolor = "#ffffdd">
"#ffffdd">OS</td>
OS</td>
61 </tr>
62
63 <tr>
64 <?php
65

 2003 Prentice Hall, Inc.


All rights reserved.
66 // print each form field’s value
50
67 print(
print( "<td>$fname $lname</td>
Outline
68 <td>$email
<td>$email</td>
$email</td>
69 <td>$phone</td>
70 <td>$os</td>" ); form.php
71 ?> (4 of 4)
72 </tr>
73 </table>
74
75 <br /><br /><br />
76 <div style = "font-
"font-size: 10pt; text-
text-align: center">
center">
77 This is only a sample form.
78 You have not been added to a mailing list.
79 </div>
</div>
80 </body>
81 </html>

 2003 Prentice Hall, Inc.


All rights reserved.
51

26.5 Form Processing and Business Logic


Fig. 26.14 Obtaining user input through forms.

 2003 Prentice Hall, Inc. All rights reserved.


52

26.6 Verifying a Username and Password

• Private website
– Only accessible to certain individuals
– Encrypt username and password data when sending, storing
and retrieving for increased security
• Implementing password checking
– Login information stored in file
• fopen function
• Read, write, append modes
– Store data using fputs
• \n newline character
– Close files when done
• fclose function

 2003 Prentice Hall, Inc. All rights reserved.


53

26.6 Verifying a Username and Password

• Implementing password checking, cont.


– Trim newline character
• chop function
– Split string into substrings given a certain delimiter
• split function
– If username/password match list, allow access

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
54
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd">
Outline
3
4 <!--
<!-- Fig. 26.15: password.html -->
-->
5 <!--
<!-- XHTML form sent to password.php for verification
verification -->
--> password.html
6 (1 of 4)
7 <html xmlns = "http://www.w3.org/1999/xhtml">
"http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Verifying
<title>Verifying a username and a password.</title>
password.</title>
10
11 <style type = "text/css">
"text/css">
12 td { background-
background-color: #DDDDDD }
13 </style>
14 </head>
15
16 <body style = "font-
"font-family: arial">
arial">
17 <p style = "font-
"font-size: 13pt">
13pt">
18 Type in your username and password below.
19 <br />
20 <span style = "color: #0000FF; font-
font-size:
size: 10pt;
21 font-
font-weight: bold">
bold">
22 Note that password will be sent as plain text
23 </span>
24 </p>
25

 2003 Prentice Hall, Inc.


All rights reserved.
26 <!--
<!-- post form data to password.php -->
-->
55
27 <form action = "password.php" method = "post">
"post">
Outline
28 <br />
29
Form data is posted to password.php.
30 <table border = "0" cellspacing = "0" password.html
31 style = "height: 90px; width: 123px; (2 of 4)
32 font-
font-size: 10pt" cellpadding = "0">
"0">
33
34 <tr>
35 <td colspan = "3">
"3">
36 <strong>Username:
<strong>Username:</strong>
Username:</strong>
37 </td>
38 </tr>
39
40 <tr>
41 <td colspan = "3">
"3">
42 <input size = "40" name = "USERNAME"
43 style = "height: 22px; width: 115px" />
44 </td>
45 </tr>
46

 2003 Prentice Hall, Inc.


All rights reserved.
47 <tr>
56
48 <td colspan = "3">
"3">
Outline
49 <strong>Password:
<strong>Password:</strong>
Password:</strong>
50 </td>
51 </tr> password.html
52 (3 of 4)
53 <tr>
54 <td colspan = "3">
"3">
55 <input size = "40" name = "PASSWORD"
56 style = "height: 22px; width: 115px"
57 type = "password" />
58 <br/></td>
59 </tr>
60
61 <tr>
62 <td colspan = "1">
"1">
63 <input type = "submit" name = "Enter"
64 value = "Enter" style = "height: 23px;
65 width: 47px" />
66 </td>
67 <td colspan = "2">
"2">
68 <input type = "submit" name = "NewUser"
69 value = "New User"
70 style = "height: 23px" />
71 </td>

 2003 Prentice Hall, Inc.


All rights reserved.
72 </tr>
57
73 </table>
Outline
74 </form>
75 </body>
76 </html> password.html
(4 of 4)

 2003 Prentice Hall, Inc.


All rights reserved.
58

26.6 Verifying a Username and Password


Fig. 26.15 XHTML form for obtaining a username and password.

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
59
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd"> Outline
3
4 <!--
<!-- Fig. 26.16: password.php -->
-->
5 <!--
<!-- Searching a database for usernames and
and passwords. -->
--> password.php
6 (1 of 7)
7 <html xmlns = "http://www.w3.org/1999/xhtml">
"http://www.w3.org/1999/xhtml">
8 <head> Variable names, when preceded by the logical
9 <?php negation operator (!), return true if they are empty
10 extract( $_POST ); or set to 0. This checks if a user has submitted a form
11 without specifying a username or password.
12 // check if user has left USERNAME or PASSWORD field blank
13 if ( !$USERNAME || !$PASSWORD ) { Function fieldsBlank is called if the user has
14 fieldsBlank(); submittedisset
an incomplete formthe
to notify the user
Function tests whether user has
15 die(); that all form fields must be completed.
pressed the New User button, indicating that a
16 }
new user must be added.
17
18 // check if the New User button wasTo add a
clicked new user, we open the file
19 if ( isset( $NewUser ) ) { password.txt in append mode and assign the
20 file handle that is returned to variable $file.
21 // open password.txt for writing
writing using append mode
22 if ( !( $file = fopen( "password.txt",
"password.txt",
23 "a" ) ) ) {
24

 2003 Prentice Hall, Inc.


All rights reserved.
25 // print error message and terminate script
60
26 // execution if file cannot be opened
Outline
27 print(
print( "<title>Error</title></head><body>
28 Could not open password file
29 </body></html>" ); password.php
30 die(); Print an error message and terminate script
(2 ofexecution
7)
31 } if the file cannot be opened.
32
33 // write username and password to file and
34 // call function userAdded
35 fputs( $file, "$USERNAME,$PASSWORD\
"$USERNAME,$PASSWORD\n" );
36 userAdded( $USERNAME );
37 }
38 else { Function userAdded is called to print a message to the
Function fputs writes the name and password to the
39 user to indicate that the username and password were
text file..
40 // if a new user isadded to theadded,
not being file. open file
41 // for reading
42 if ( !( $file = fopen( "password.txt",
"password.txt",
43 "r" ) ) ) {
44 print(
print( "<title>Error</title></head>
45 <body>Could not open password file
46 </body></html>" );
47 die();
48 }
49

 2003 Prentice Hall, Inc.


All rights reserved.
50 $userVerified = 0;
61
51
Outline
52 // read each line in file and check
Before username
entering the while loop, variable
53 // and password Function$userVerified
fgets reads a line from
is set to 0the
. text file.
54 while ( !feof( $file ) && !$userVerified
The result ) {
is assigned to variable $line. password.php
55 (3 of 7)
56 // read line from file
57
The while loop executes as long
$line = fgets( Function chop
$file, 255 );
);
as the
removes thethere are more
newline character
58
lines in the filefrom
to read and of
the end variable $userVerified is
the line.
Function
still split is called to separate the string at the
0 or empty.
59 // remove newline character from end of line
specified delimiter (in this case, a comma). The
60 $line = chop( $line ); );
The username
resulting array is stored inentered by the user
array $field . is tested
61
against the one returned in the text file (stored
62 // split username and password
in the first element of the array). If they match,
63 $field = split( ",",",", $line, 2 ););
variable $userVerified is set to 1.
64
65 // verify username
66 if ( $USERNAME == $field[ 0 ] ) {
67 $userVerified = 1;
68
69 If function
// call function checkPassword to verify checkPassword returns true, function
70 // user’s password accessGranted is called to notify the client that
71 permission
if ( checkPassword( $PASSWORD, $field ) has been granted. Otherwise, function
72 == true ) wrongPassword is called.
73 accessGranted( $USERNAME );
74 else
Function checkPassword is called to verify
75 wrongPassword();
wrongPassword();
the user’s password. Variable $PASSWORD and
array $field are passed to the function.  2003 Prentice Hall, Inc.
All rights reserved.
76 }
62
77 }
Outline
78 If variable $userVerified has not been set to a
79 // close text value otherAfter
file than 0the while loop
, function has executed,
accessDenied is function
80 fclose( $file
fclose is called to close the file.
);called to notify the client that access has been password.php
81 denied. (4 of 7)
82 // call function accessDenied if username has
83 // not been verified
Function checkPassword compares the user’s
84 if ( !$userVerified )
password to the password in the file. If they match,
85 accessDenied();
true is returned, whereas false is returned if they
86 }
do not.
87
88 // verify user password and return a boolean
89 function checkPassword( $userpassword, $filedata )
90 {
91 if ( $userpassword
$userpassword == $filedata[ 1 ] )
92 return true;
true;
93 else
94 return false;
false;
95 }
96

 2003 Prentice Hall, Inc.


All rights reserved.
97 // print a message indicating the user has been added
63
98 function userAdded( $name )
Outline
99 {
100 print(
print( "<title>Thank You</title></head>
101 "fontFunction
-family: userAdded
<body style = \"font- arial; prints a message to the password.php
102 font-
font-size: 1em; client
color: indicating
blue\
blue \"> that the user has been added. (5 of 7)
103 <strong>You have been added
104 to the user list, $name. Function accessGranted prints a
105 <br />Enjoy the site.</strong>"message
); to the client indicating that
106 } permission has been granted.
107
108 // print a message indicating
indicating permission
109 // has been granted
110 function accessGranted( $name )
111 {
112 print(
print( "<title>Thank You</title></head>
113 <body style = \"font-
"font-family: arial;
114 font-
font-size: 1em; color: blue\
blue\">
115 <strong>Permission has been
116 granted, $name. <br />
117 Enjoy the site.</strong>" );
118 }
119

 2003 Prentice Hall, Inc.


All rights reserved.
120 // print a message indicating password is invalid
64
121 function wrongPassword()
Outline
122 {
Function wrongPassword prints a message to the
123 print(
print( "<title>Access Denied</title></head>
client indicating that the password is invalid.
password.php
124 <body style = \"font-
"font-family: arial;
125 font-
font-size: 1em; color: red\
red\"> (6 of 7)
126 <strong>You entered an invalid
127 password.<br />Access has
128 been denied.</strong>" );
129 }
130
131 // print a message indicating access
access has been denied
132 function accessDenied()
133 {
134 print(
print( "<title>Access Denied</title></head>
135 <body style = \"font-
"font-family: arial;
136 font-
font-size: 1em; color: red\
red\">
137 <strong>
138 You were denied access to this server.
139 <br /></strong>" ); Function accessDenied prints a message to the
140 } client indicating that access has been denied.
141

 2003 Prentice Hall, Inc.


All rights reserved.
142 // print a message indicating that fields
65
143 // have been left blank
Function fieldsBlank prints a message toOutline the
144 function fieldsBlank()
client indicating that all form fields have not been
145 {
completed.
146 print(
print( "<title>Access Denied</title></head> password.php
147 <body style = \"font-
"font-family: arial; (7 of 7)
148 font-
font-size: 1em; color: red\
red\">
149 <strong>
150 Please fill in all form fields.
151 <br /></strong>" );
152 }
153 ?>
154 </body>
155 </html>

 2003 Prentice Hall, Inc.


All rights reserved.
66

26.6 Verifying a Username and Password


Fig. 26.16 Verifying a username and password.

 2003 Prentice Hall, Inc. All rights reserved.


1 account1,password1
67
2 account2,password2 Outline
3 account3,password3
4 account4,password4
5 account5,password5 password.txt
6 account6,password6 (1 of 1)
7 account7,password7
8 account8,password8
9 account9,password9
10 account10,password10

 2003 Prentice Hall, Inc.


All rights reserved.
68

26.7 Connecting to a Database

• Databases
– Store and maintain data
– MySQL is a free database product
– PHP supports many database operations
• Access databases from Web pages

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
69
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd">
Outline
3
4 <!--
<!-- Fig. 26.18: data.html -->
-->
5 <!--
<!-- Querying a MySQL Database -->
--> data.html
6 (1 of 2)
7 <html xmlns = "http://www.w3.org/1999/xhtml"
"http://www.w3.org/1999/xhtml">
p://www.w3.org/1999/xhtml">
8 <head>
9 <title>Sample
<title>Sample Database Query</title>
Query</title>
10 </head>
11
12 <body style = "background-
"background-color: #F0E68C">
#F0E68C">
13 <h2 style = "font-
"font-family: arial color: blue">
blue">
14 Querying a MySQL
MySQL database.
15 </h2>
16
17 <form method = "post" action = "database.php">
"database.php">
18 <p>Select
<p>Select a field to display:
19
20 <!--
<!-- add a select box containing options -->
-->
21 <!--
<!-- for SELECT query -->
-->

 2003 Prentice Hall, Inc.


All rights reserved.
22 <select name = "select">
"select">
70
23 <option selected = "selected">
"selected">*</option>
Outline
24 <option>ID
<option>ID</option>
ID</option>
25 <option>Title
<option>Title</option>
Title</option> Select box containing options for a SELECT
26 <option>Category
<option>Category</option>
Category</option> query. data.html
27 <option>ISBN
<option>ISBN</option>
ISBN</option> (2 of 2)
28 </select>
29 </p>
30
31 <input type = "submit" value = "Send Query"
32 style = "background-
"background-color: blue;
33 color: yellow; font-
font-weight: bold" />
34 </form>
35 </body>
36 </html>

 2003 Prentice Hall, Inc.


All rights reserved.
71

26.7 Connecting to a Database


Fig. 26.18 Form to query a MySQL database.

 2003 Prentice Hall, Inc. All rights reserved.


72

26.7 Connecting to a Database

• Interacting with databases


– SQL
• Structured Query Language
• Used to manipulate databases
– Several useful functions
• mysql_connect
• mysql_select_db
• mysql_query
• mysql_error
• mysql_fetch_row
• mysql_close

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
73
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd"> Outline
3
4 <!--
<!-- Fig. 26.19: database.php -->
-->
5 <!--
<!-- Program to query a database and -->
--> database.php
6 <!--
<!-- send results
results to the client. -->
--> (1 of 3)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
"http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Search
<title>Search Results</title>
Results</title>
11 </head>
12
13 <body style = "font-
"font-family: arial, sans-
sans-serif"
14 style = "background
"background-color: #F0E68C">
#F0E68C">
15 <?php Build the select query and assign the
16 string to variable $query.
17 extract( $_POST ); Function mysql_connect returns a database
18 handle which represents PHP’s connection to a
19 // build SELECT query database. If this connection is not made, function
20 $query = "SELECT " . $select . " FROM
dieBooks";
Books";
is called to terminate script execution.
21
22 // Connect to MySQL
23 if ( !( $database
$database = mysql_connect(
mysql_connect( "localhost",
"localhost",
24 "httpd",
"httpd", "" ) ) )
25 die(
die( "Could not connect to database" );

 2003 Prentice Hall, Inc.


All rights reserved.
26
74
// open Products database
27
Outline
28 if ( !mysql_select_db(
mysql_select_db( "Products", Function) mysql_query
"Products", $database ) returns an object
29 die( containing
die( "Could not open Products database" ); the result set of the query, which
30 we assign to variable $result. database.php
31 // query Products database (2 of 3)
if ( !( $result
$result = mysql_query(( $query, $database ) ) ) {
32
Functionmysql_query
mysql_select_db is called to specify the
33 print(
print( "Could not execute query! <br />" );
database to be queried.
34 die(
die( mysql_error()
mysql_error() );
35 }
36 ?>
37
38 <h3 style = "color: blue">
blue">
39 Search Results</h3>
Results</h3>
40
41 <table border = "1" cellpadding = "3" cellspacing = "2"
42 style = "background-
"background-color: #ADD8E6">
#ADD8E6">
43
44 <?php The for loop iterates through each
45 record in the result set while
46 // fetch each record in result set constructing an XHTML table from
47 for ( $counter = 0; the results. Variable $counter is
48 mysql_fetch_row( $result incremented
$row = mysql_fetch_row( ); by one for each row
49 $counter++ ){ retrieved. Function mysql_fetch_row returns an
50 array containing the elements of each
row in the result set of our query
($result).
 2003 Prentice Hall, Inc.
All rights reserved.
51 // build table to display results
75
print(
print( "<tr>" );
52
Outline
53
54 foreach ( $row as $key => $value )
55 print(
print( "<td>$value</td>" ); database.php
56 (3 of 3)
57 print(
print( "</tr>" );
The foreach loop iterates through the
58 }
array containing the elements of each row
59
and prints out each element in an
60 mysql_close( $databaseThe
mysql_close( ); total number of results are printed to the
individual table cell.
61 ?> client.
62
63 </table>
64
65 <br />Your
/>Your search yielded <strong>
66 <?php print(
print( "$counter" ) ?> results.<br
results.<br /><br /></strong>
67
68 <h5>Please
<h5>Please email comments to
69 <a href = "mailto:deitel@deitel.com">
"mailto:deitel@deitel.com">
70 Deitel and Associates, Inc.
71 </a>
72 </h5>
73
74 </body>
75 </html>

 2003 Prentice Hall, Inc.


All rights reserved.
76

26.7 Connecting to a Database


Fig. 26.19 Querying a database and displaying the results.

 2003 Prentice Hall, Inc. All rights reserved.


77

26.8 Cookies

• Cookies
– Store information on client computer
– Track preferences and other information
– Stored as text files on hard drive
– Never store sensitive information, such as credit card
numbers, in a cookie
• Security risk
• Cookies and PHP
– setcookie function
• Name
• Value
• Expiration date

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
78
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd"> Outline
3
4 <!--
<!-- Fig. 26.20: cookies.html -->
-->
5 <!--
<!-- Writing a Cookie -->
--> cookies.html
6 (1 of 2)
7 <html xmlns = "http://www.w3.org/1999/xhtml"
"http://www.w3.org/1999/xhtml">
//www.w3.org/1999/xhtml">
8 <head>
9 <title>Writing
<title>Writing a cookie to the client computer</title>
computer</title>
10 </head>
11
12 <body style = "font-
"font-family: arial, sans-
sans-serif;
13 background-
background-color: #99CCFF">
#99CCFF">
14
15 <h2>Click
<h2>Click Write Cookie to save your cookie data.</h2>
data.</h2>
16

 2003 Prentice Hall, Inc.


All rights reserved.
17 <form method = "post" action = "cookies.php"
79
18 style = "font-
"font-size: 10pt">
10pt">
Outline
19 <strong>Name:
<strong>Name:</strong><br
Name:</strong><br /> Form data is posted to cookies.php.
20 <input type = "text" name = "NAME" /><br
/><br />
21 cookies.html
22 <strong>Height:
<strong>Height:</s
Height:</strong><br
</strong><br /> (2 of 2)
23 <input type = "text" name = "HEIGHT" /><br
/><br />
24
25 <strong>Favorite
<strong>Favorite Color:</strong><br
Color:</strong><br />
26 <input type = "text" name = "COLOR" /><br
/><br />
27
28 <input type = "submit" value = "Write Cookie"
Cookie"
29 style = "background-
"background-color: #F0E86C; color: navy;
30 font-
font-weight: bold" /></p>
31 </form>
32 </body>
33 </html>

 2003 Prentice Hall, Inc.


All rights reserved.
80

26.8 Cookies
Fig. 26.20 Gathering data to be written as a cookie.

 2003 Prentice Hall, Inc. All rights reserved.


1 <?php
81
2 // Fig. 26.21: cookies.php Outline
3 // Program to write a cookie to a client's machine
4
5 extract( $_POST ); cookies.php
6 // write each form field’s value to a cookie and set the (1 of 2)
7 // cookie’s expiration date
8 setcookie(
setcookie( "Name",
"Name", $NAME, time() + 60 * 60 * 24 * 5 );
9 setcookie(
setcookie( "Height",
"Height", $HEIGHT, time() + 60 * 60 * 24 * 5 );
10 setcookie(
setcookie( "Color",
"Color", $COLOR, time() + 60 * 60 * 24 * 5 );
11 ?> Function setcookie takes the name of the
12 cookie to be set as the first argument,
13 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 followed by the value to be stored in the
1.0 Transitional//EN"
14 "http://www.w3.org/TR/xhtml1/DTD/xhtml1- cookie. The
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd"> optional third argument specifies
15 the expiration date of the cookie.
16 <html xmlns = "http://www.w3.org/1999/xhtml">
"http://www.w3.org/1999/xhtml">
17 <head>
18 <title>Cookie
<title>Cookie Saved</title>
Saved</title>
19 </head>
20
21 <body style = "font-
"font-family: arial, sans-
sans-serif">
serif">
22 <p>The
<p>The cookie has been set with the following data:</p>
data:</p>
23

 2003 Prentice Hall, Inc.


All rights reserved.
24 <!--
<!-- print each form field’s value -->
-->
82
25 <br /><span style = "color: blue">
blue">Name:</span>
Name:</span>
Each form field’s value is printed to Outline
26 <?php print(
print( $NAME ) ?><br
?><br /> confirm the data that has been set as a
27 cookie with the user.
28 <span style = "color: blue">
blue">Height:</span>
Height:</span> cookies.php
29 <?php print(
print( $HEIGHT
$HEIGHT ) ?><br
?><br /> (2 of 2)
30
31 <span style = "color: blue">
blue">Favorite Color:</span>
Color:</span>
32
33 <span style = "color: <?php print(
print( "$COLOR\
"$COLOR\">$COLOR" ) ?>
34 </span><br />
35 <p>Click
<p>Click <a href = "readCookies.php">
"readCookies.php">here</a
here</a>
</a>
36 to read the saved cookie.</p>
cookie.</p>
37 </body>
38 </html>
Hyperlink to readCookies.php.

 2003 Prentice Hall, Inc.


All rights reserved.
83

26.8 Cookies
Fig. 26.21 Writing a cookie to the client.

 2003 Prentice Hall, Inc. All rights reserved.


84

26.8 Cookies

• Reading cookies
– $_COOKIE environment variable
• Array
– foreach loop to access each element
• Split into key and value

 2003 Prentice Hall, Inc. All rights reserved.


85

26.8 Cookies

• Cookie storage
– Internet Explorer
• Stores cookies in Cookies directory
• Text file

 2003 Prentice Hall, Inc. All rights reserved.


86

26.8 Cookies
Fig. 26.22 Cookies directory before a cookie is written.

Fig. 26.23 Cookies directory after a cookie is written.

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
87
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd"> Outline
3
4 <!--
<!-- Fig. 26.24: readCookies.php -->
-->
5 <!--
<!-- Program to read cookies from the client's
client's computer -->
--> readCookies.php
6 (1 of 2)
7 <html xmlns = "http://www.w3.org/1999/xhtml">
"http://www.w3.org/1999/xhtml">
8 <head><title>Read
<head><title>Read Cookies</title></head>
Cookies</title></head>
9
10 <body style = "font-
"font-family: arial, sans-
sans-serif">
serif">
11
12 <p>
13 <strong>
14 The following data is saved in a cookie on your
15 computer.
16 </strong>
17 </p>
18

 2003 Prentice Hall, Inc.


All rights reserved.
19 <table border = "5" cellspacing = "0" cellpadding = "10">
"10">
88
20 <?php
The foreachPHPloop iterates
creates through
array the $_COOKIE
$_COOKIE which contains Outline
21
array and prints the name
all cookie andindexed
values value ofbyeach
theircookie
names.
22 // iterate through array $_COOKIE and print
in an XHTML table.
23 // name and value of each cookie readCookies.php
24 foreach ( $_COOKIE as $key =>
=> $value ) (2 of 2)
25 print(
print( "<tr>
26 <td bgcolor=\
bgcolor=\"#F0E68C\
"#F0E68C\">$key</td>
27 <td bgcolor=\
bgcolor=\"#FFA500\
"#FFA500\">$value</td>
28 </tr>" );
29 ?>
30
31 </table>
</table>
32 </body>
33 </html>

 2003 Prentice Hall, Inc.


All rights reserved.
89

26.8 Cookies
Fig. 26.24 Displaying the cookie’s content.

 2003 Prentice Hall, Inc. All rights reserved.


90

26.9 Dynamic Content in PHP

• Dynamically alter XHTML content


– Form’s action property set to same page that contains it
– Perform different actions when page is loaded and form is
submitted
• isset variable
– Check for errors
• Write different XHTML when errors encountered
– $$variable syntax
• References variable whose name equals the value of $variable
– If input is valid, make MySQL database calls

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
91
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd"> Outline
3
4 <!--
<!-- Fig. 26.25: dynamicForm.php -->
-->
5 <!--
<!-- Form for use with the form.php program -->
--> dynamicForm.php
6 (1 of 9)
7 <html xmlns = "http://www.w3.org/1999/xhtml">
"http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Sample
<title>Sample form to take user input in XHTML</title>
XHTML</title>
10 </head>
11
12 <body>
13 <?php
14 extract ( $_POST );
Build array of options for the form.
15 $iserror = false;
false;
16
17 // array of book titles
18 $booklist = array(
array( "Internet and WWW How to Program 3e",
3e",
19 "C++ How to Program 4e",
4e",
20 "Java How to Program 5e",
5e",
21 "XML How to Program 1e" );
22

 2003 Prentice Hall, Inc.


All rights reserved.
23 // array of possible operating systems
92
24 $systemlist = array(
array( "Windows XP",
XP",
Outline
25 "Windows 2000",
2000",
26 "Windows 98",
98",
27 "Linux",
"Linux", dynamicForm.php
28 "Other");
"Other"); (2 of 9)
29
30 // array of name and alt values for the text input fields
31 $inputlist = array(
array( "fname" => "First Name",
Name",
32 "lname" => "Last Name",
Name",
If the page is being loaded as a result of a form
33 "email" => "Email",
"Email",
submission, do error
Check for errors checking and
or omissions then field
in form retrieve
34 "phone" => "Phone" );
information
input. from the database.
35
36 if ( isset ( $submit ) ) {
37 if ( $fname == "" ) {
38 $formerrors[ "fnameerror" ] = true;
true;
39 $iserror = true;
true;
40 }
41
42 if ( $lname == "" ) {
43 $formerrors[ "lnameerror"
"lnameerror" ] = true;
true;
44 $iserror = true;
true;
45 }
46

 2003 Prentice Hall, Inc.


All rights reserved.
47 if ( $email == "" ) {
93
48 $formerrors[ "emailerror" ] = true;
true;
Outline
49 $iserror = true;
true;
50 }
51 dynamicForm.php
52 if ( !ereg( "^\
"^\([0-
([0-9]{3}\
9]{3}\)[0-
)[0-9]{3}-
9]{3}-[0-
[0-9]{4}$",
9]{4}$", $phone ) ) { (3 of 9)
53 $formerrors[ "phoneerror" ] = true;
true;
54 $iserror = true;
true;
55 }
56
If there were no errors, query the MySQL
57 if ( !$iserror ) {
database.
58
59 // build INSERT query
60 $query = "INSERT INTO contacts " .
61 "( LastName, FirstName,
FirstName, Email, Phone, Book, OS ) " .
62 "VALUES ( '$lname', '$fname', '$email', " .
63 "'" . quotemeta( $phone ) . "', '$book', '$os' )";
)";
64
65 // Connect to MySQL
66 if ( !( $database = mysql_connect(
mysql_connect( "localhost",
"localhost",
67 "httpd",
"httpd", "" ) ) )
68 die( "Could not connect to database" );
69
70 // open MailingList database
71 if ( !mysql_select_db( "MailingList",
"MailingList", $database ) )
72 die( "Could not open MailingList database" );

 2003 Prentice Hall, Inc.


All rights reserved.
73
94
74 // execute query in MailingList database
Outline
75 if ( !( $result = mysql_query( $query, $database ) ) ) {
76 print( "Could not execute query! <br />" );
77 die( mysql_error() ); dynamicForm.php
78 } (4 of 9)
79
80 print(
print( "<p>Hi
81 <span style = 'color: blue'>
82 <strong>$fname</strong></span>.
83 Thank you for completing the survey.<br />
84
85 You have been added to the
86 <span style = 'color: blue'>
87 <strong>$book</strong></span>
88 mailing list.
89 </p>
90 <strong>The following information has been saved
91 in our database:</strong><br />
92
93 <table border = '0' cellpadding = '0' cellspacing = '10'>
94 <tr>
95 <td bgcolor = '#ffffaa'>Name</td>
96 <td bgcolor = '#ffffbb'>Email</td>
'#ffffbb'>Email</td>
97 <td bgcolor = '#ffffcc'>Phone</td>

 2003 Prentice Hall, Inc.


All rights reserved.
98 <td bgcolor = '#ffffdd'>OS</td>
95
99 </tr>
Outline
100 <tr>
101
102 <!--
<!-- print each form field’s value -->
--> dynamicForm.php
103 <td>$fname $lname</td> (5 of 9)
104 <td>$email</td>
105 <td>$phone</td>
106 <td>$os</td>
107 </tr></table>
108
109 <br /><br /><br />
110 <div style = 'font-
'font-size: 10pt; text-
text-align: center'>
111 <div style = 'font-
'font-size : 18pt'>
112 <a href = 'formDatabase.php'>
113 Click here to view entire database.</a></div>
Halt the script so the form-generation code
114 This is only a sample form.
does not execute.
115 You have not been added to a mailing list.
116 </div></body></html>" );
117 die();
118 }
119 }
120
121 print(
print( "<h1>This is a sample registration form.</h1>
122 Please fill in all fields and click Register." );

 2003 Prentice Hall, Inc.


All rights reserved.
123
96
124 if ( $iserror ) {
Outline
125 print(
print( "<br /><span style = 'color : red'>
126 Fields with * need to be filled in properly.</span>" );
127 } dynamicForm.php
128 (6 of 9)
129 print(
print( "<!--
"<!-- post form data to form.php -->
-->
130 <form method = 'post' action = 'dynamicform.php'>
131 <img src = 'images/user.gif' alt = 'User' /><br />
132 <span style = 'color: blue'>
133 Please fill out the fields below.<br />
134 </span>
135
136 <!--
<!-- create four text boxes for user input -->"
-->" );
Fill in the forms using $$variable syntax.
137 foreach ( $inputlist as $inputname => $inputalt ) {
138 $inputtext = $inputvalues[ $inputname ];
139
140 print(
print( "<img src = 'images/$inputname.gif'
If the form input contained errors, place a red
141 alt = '$inputalt' /><input type = 'text'
asterisk (*) next to the text field.
142 name = '$inputname' value = '" . $$inputname . "' />" );
143
144 if ( $formerrors[ ( $inputname )."error"
)."error" ] == true )
145 print(
print( "<span style = 'color : red'>*</span>" );
146
147 print(
print( "<br />" );
148 }

 2003 Prentice Hall, Inc.


All rights reserved.
149
97
150 print(
print( "<span style = 'font-
'font-size : 10pt" );
Outline
151
152 if ( $formerrors[ "phoneerror" ] )
153 print(
print( "; color : red" ); dynamicForm.php
154 (7 of 9)
155 print(
print( "'>Must be in the form (555)555-
(555)555-5555
156 </span><br /><br
/><br />
157
158 <img src = 'images/downloads.gif'
159 alt = 'Publications' /><br />
160
161 <span style = 'color: blue'>
162 Which book would you like information about?
163 </span><br />
164
165 <!--
<!-- create drop-
drop-down list containing book names -->
-->
166 <select name = 'book'>" );
167
Make sure the correct book is selected in the
168 foreach ( $booklist as $currbook ) {
dropdown box.
169 print(
print( "<option" );
170
171 if ( ( $currbook == $book ) )
172 print(
print( " selected = 'true'" );
173

 2003 Prentice Hall, Inc.


All rights reserved.
174 print(
print( ">$currbook</option>" );
98
175 }
Outline
176
177 print(
print( "</select><br /><br />
178 <img src = 'images/os.gif' alt = 'Operating System' /> dynamicForm.php
179 <br /><span style = 'color: blue'> (8 of 9)
180 Which operating system are you currently using?
181 <br /></span>
182
183 <!--
<!-- create five radio buttons -->"
-->" );
184
185 $counter = 0;
186
187 foreach ( $systemlist as $currsystem ) {
188 print
Make sure the correct OS is checked in the
print( "<input type = 'radio' name = 'os'
189 value =
checkbox.
'$currsystem'" );
190
191 if ( $currsystem == $os ) print(
print( "checked = 'checked'" );
192 if ( $iserror && $counter == 0 ) print(
print( "checked = 'checked'" );
193
194 print(
print( " />$currsystem" );
195
196 if ( $counter == 2 ) print(
print( "<br />" );
197 $counter++;
198 }
199

 2003 Prentice Hall, Inc.


All rights reserved.
200 print(
print( "<!--
"<!-- create a submit button -->
-->
99
201 <br />
Outline
202 <input type = 'submit' name = 'submit' value = 'Register' />
203 </form></body></html>" );
204 ?> dynamicForm.php
(9 of 9)

 2003 Prentice Hall, Inc.


All rights reserved.
100

26.9 Dynamic Content in PHP


Fig. 26.25 Dynamic form using PHP.

 2003 Prentice Hall, Inc. All rights reserved.


101

26.9 Dynamic Content in PHP


Fig. 26.25 Dynamic form using PHP.

 2003 Prentice Hall, Inc. All rights reserved.


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
102
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
transitional.dtd"> Outline
3
4 <!--
<!-- Fig. 26.26: formDatabase.php -->
-->
5 <!--
<!-- Program to query a database and -->
--> formDatabase.php
6 <!--
<!-- send results to the client. -->
--> (1 of 3)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
"http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Search
<title>Search Results</title>
Results</title>
11 </head>
12
13 <body style = "font-
"font-family: arial, sans-
sans-serif"
14 style = "background
"background-
round-color: #F0E68C">
#F0E68C">
15 <?php
16 Build the query string.
17 extract( $_POST );
18
19 // build SELECT query
20 $query = "SELECT * FROM contacts";
contacts";
21
22 // Connect to MySQL
23 if ( !( $database
$database = mysql_connect( "localhost",
"localhost",
24 "httpd",
"httpd", "" ) ) )
25 die( "Could not connect to database" );

 2003 Prentice Hall, Inc.


All rights reserved.
26
103
27 // open MailingList database
Outline
28 if ( !mysql_select_db( "MailingList",
"MailingList", $database ) )
29 die( "Could not open MailingList database" );
30 formDatabase.php
31 // query MailingList database (2 of 3)
32 if ( !( $result = mysql_query( $query, $database ) ) ) {
33 print(
print( "Could not execute query! <br />" );
34 die( mysql_error() );
35 }
36 ?>
37
38 <h3 style = "color: blue">
blue">
39 Mailing List Contacts</h3>
Contacts</h3>
40
41 <table border = "1" cellpadding = "3" cellspacing = "2"
42 style = "background-
"background-color: #ADD8E6">
#ADD8E6">
43
44 <tr>
45 <td>ID
<td>ID</td>
ID</td>
46 <td>Last
<td>Last Name</td>
Name</td>
47 <td>First
<td>First Name</td>
Name</td>
48 <td>E
<td>E-mail Address</td>
Address</td>
49 <td>Phone
<td>Phone Number</td>
Number</td>
50 <td>Book
<td>Book</td>
Book</td>

 2003 Prentice Hall, Inc.


All rights reserved.
51 <td>Operating
<td>Operating System</td>
System</td>
104
52 </tr>
Outline
53 <?php Retrieve each mailing list
54 member record from the
55 // fetch each record in resultdatabase.
set formDatabase.php
56 for ( $counter = 0; (3 of 3)
57 $row = mysql_fetch_row( $result );
58 $counter++ ){
59
Dynamically create a table
60 // build table to display results
containing each mailing list
61 print(
print( "<tr>" );
member.
62
63 foreach ( $row as $key => $value )
64 print(
print( "<td>$value</td>" );
65
66 print(
print( "</tr>" );
67 }
68
69 mysql_close( $database );
70 ?>
71
72 </table>
73
74 </body>
75 </html>

 2003 Prentice Hall, Inc.


All rights reserved.
105

26.9 Dynamic Content in PHP


Fig. 26.26 Displaying the MailingList database.

 2003 Prentice Hall, Inc. All rights reserved.


106

26.10 Operator Precedence


Operator Type Associativity
new constructor none
[] subscript right to left
~ bitwise not right to left
! not
++ increment
-- decrement
- unary negative
@ error control
* multiplication left to right
/ division
% modulus
+ addition left to right
- subtraction
. concatenation
<< bitwise shift left left to right
>> bitwise shift right
< less than none
> greater than
<= less than or equal
>= greater than or equal
== equal none
!= not equal
=== identical
!== not identical
Fig. 26.27 PHP operator precedence and associativity.

 2003 Prentice Hall, Inc. All rights reserved.


107

26.10 Operator Precedence


Operator Type Associativity
& bitwise AND left to right
^ bitwise XOR left to right
| bitwise OR left to right
&& logical AND left to right
|| logical OR left to right
= assignment left to right
+= addition assignment
-= subtraction assignment
*= multiplication assignment
/= division assignment
&= bitwise AND assignment
|= bitwise OR assignment
^= bitwise exclusive OR assignment
.= concatenation assignment
<<=
bitwise shift left assignment
>>=
bitwise shift right assignment
and logical AND left to right
xor exclusive OR left to right
or logical OR left to right
, list left to right
Fig. 26.27 PHP operator precedence and associativity.

 2003 Prentice Hall, Inc. All rights reserved.

You might also like