1 chapter 26 - php - csuohio.edueecs.csuohio.edu/~sschung/cis408/lecturenotes_php-26.pdf · 1...
TRANSCRIPT
2003 Prentice Hall, Inc. All rights reserved.
1
Chapter 26 - PHP
Outline26.1 Introduction
26.2 PHP
26.3 String Processing and Regular Expressions
26.4 Viewing Client/Server Environment Variables26.5 Form Processing and Business Logic
26.6 Verifying a Username and Password
26.7 Connecting to a Database
26.8 Cookies26.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.
Outline51 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"//W3C//DTD XHTML 1.0 Strict//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----strict.dtd"strict.dtd"strict.dtd"strict.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.1: first.php Fig. 26.1: first.php Fig. 26.1: first.php Fig. 26.1: first.php -------->>>>
5 <!<!<!<!-------- Our first PHP script Our first PHP script Our first PHP script Our first PHP script -------->>>>
6
7 <?php<?php<?php<?php
8 $name = $name = $name = $name = "LunaTic""LunaTic""LunaTic""LunaTic";;;; // declaration// declaration// declaration// declaration
9 ?>?>?>?>
10
11 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>
12 <head> <head> <head> <head>
13 <title> <title> <title> <title>A simple PHP documentA simple PHP documentA simple PHP documentA simple PHP document</title></title></title></title>
14 </head> </head> </head> </head>
15
16 <body styl <body styl <body styl <body style = e = e = e = "font"font"font"font----size: 2em"size: 2em"size: 2em"size: 2em">>>>
17 <p> <p> <p> <p>
18 <strong><strong><strong><strong>
19
20 <! <! <! <!-------- print variable name’s value print variable name’s value print variable name’s value print variable name’s value -------->>>>
21 Welcome to PHP, Welcome to PHP, Welcome to PHP, Welcome to PHP, <?php<?php<?php<?php print print print print( ( ( ( "$name""$name""$name""$name" ); ); ); ); ?>?>?>?>!!!!
22 </strong> </strong> </strong> </strong>
23 </p> </p> </p> </p>
24 </body> </body> </body> </body>
25 </htm</htm</htm</html>l>l>l>
first.php
(1 of 1)
Declare variable $name
Scripting delimiters
Single-line comment
Function print outputs the value of variable $name
2003 Prentice Hall, Inc. All rights reserved.
6
26.2 PHPFig. 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.
Outline91 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.3: data.php Fig. 26.3: data.php Fig. 26.3: data.php Fig. 26.3: data.php -------->>>>
5 <!<!<!<!-------- Demonstration of PHP data types Demonstration of PHP data types Demonstration of PHP data types Demonstration of PHP data types -------->>>>
6
7 <html <html <html <html xmlns = xmlns = xmlns = xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>
8 <head><head><head><head>
9 <title><title><title><title>PHP data typesPHP data typesPHP data typesPHP data types</title></title></title></title>
10 </head></head></head></head>
11
12 <body><body><body><body>
13
14 <?php<?php<?php<?php
15
16 // declare a string, double and integer// declare a string, double and integer// declare a string, double and integer// declare a string, double and integer
17 $testString = $testString = $testString = $testString = "3"3"3"3.5 seconds".5 seconds".5 seconds".5 seconds";;;;
18 $testDouble = $testDouble = $testDouble = $testDouble = 79.279.279.279.2;;;;
19 $testInteger = $testInteger = $testInteger = $testInteger = 12121212;;;;
20 ?>?>?>?>
21
data.php
(1 of 3)
Assign a string to variable $testString
Assign a double to variable $testDoubleAssign an integer to variable $testInteger
2003 Prentice Hall, Inc.
All rights reserved.
Outline10
22 <!<!<!<!-------- print each variable’s value print each variable’s value print each variable’s value print each variable’s value -------->>>>
23 <?php<?php<?php<?php printprintprintprint( $testString ); ( $testString ); ( $testString ); ( $testString ); ?>?>?>?> is a string. is a string. is a string. is a string.<br /><br /><br /><br />
24 <?php<?php<?php<?php printprintprintprint( $testDouble ); ( $testDouble ); ( $testDouble ); ( $testDouble ); ?> ?> ?> ?> is a double.is a double.is a double.is a double.<br /><br /><br /><br />
25 <?php<?php<?php<?php printprintprintprint( $testInteger ); ( $testInteger ); ( $testInteger ); ( $testInteger ); ?> ?> ?> ?> is an integer.is an integer.is an integer.is an integer.<br /><br /><br /><br />
26
27 <br /><br /><br /><br />
28 Now, converting to other types: Now, converting to other types: Now, converting to other types: Now, converting to other types:<br /><br /><br /><br />
29 <?php<?php<?php<?php
30
31 // call function settype to convert variable // call function settype to convert variable // call function settype to convert variable // call function settype to convert variable
32 // testString to different data types // testString to different data types // testString to different data types // testString to different data types
33 printprintprintprint( ( ( ( "$testString""$testString""$testString""$testString" ); ); ); );
34 settype( $testString, settype( $testString, settype( $testString, settype( $testString, "double""double""double""double" ); ); ); );
35 printprintprintprint( ( ( ( " as a double is $testString <br />"" as a double is $testString <br />"" as a double is $testString <br />"" as a double is $testString <br />" ); ); ); );
36 printprintprintprint( ( ( ( "$testString""$testString""$testString""$testString" ); ); ); );
37 settype( $testString, settype( $testString, settype( $testString, settype( $testString, "integer""integer""integer""integer" ); ); ); );
38 printprintprintprint( ( ( ( " as an integer is $testString <br />"" as an integer is $testString <br />"" as an integer is $testString <br />"" as an integer is $testString <br />" ); ); ); );
39 settype( $testString, settype( $testString, settype( $testString, settype( $testString, "string""string""string""string" ); ); ); );
40 printprintprintprint( ( ( ( "Converting back to a string results in"Converting back to a string results in"Converting back to a string results in"Converting back to a string results in
41 $testString <br /><br />"$testString <br /><br />"$testString <br /><br />"$testString <br /><br />" ); ); ); );
42
43 $data = $data = $data = $data = "98.6 degrees""98.6 degrees""98.6 degrees""98.6 degrees";;;;
data.php
(2 of 3)Print each variable’s value
Call function settype to
convert the data type of
variable $testString to a
double.
Call function settype to
convert the data type of
variable $testString to an
integer.Convert variable $testString
back to a string
2003 Prentice Hall, Inc.
All rights reserved.
Outline11
44
45 // use type casting to cast variables to a// use type casting to cast variables to a// use type casting to cast variables to a// use type casting to cast variables to a
46 // different type // different type // different type // different type
47 printprintprintprint( ( ( ( "Now using type casting instead: <br />"Now using type casting instead: <br />"Now using type casting instead: <br />"Now using type casting instead: <br />
48 As a string As a string As a string As a string ---- " " " " . ( . ( . ( . (stringstringstringstring) $data .) $data .) $data .) $data .
49 "<br />As a double "<br />As a double "<br />As a double "<br />As a double ---- " " " " . ( . ( . ( . (doubledoubledoubledouble) $data .) $data .) $data .) $data .
50 "<br />As an integer "<br />As an integer "<br />As an integer "<br />As an integer ---- " " " " . ( . ( . ( . (integerintegerintegerinteger) $data );) $data );) $data );) $data );
51 ?>?>?>?>
52 </body> </body> </body> </body>
53 </html></html></html></html>
data.php
(3 of 3)
Use type casting to cast variable
$data to different types
2003 Prentice Hall, Inc. All rights reserved.
12
26.2 PHPFig. 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.
Outline141 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.4: operators.php Fig. 26.4: operators.php Fig. 26.4: operators.php Fig. 26.4: operators.php -------->>>>
5 <!<!<!<!-------- Demonstration of operators Demonstration of operators Demonstration of operators Demonstration of operators -------->>>>
6
7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "h"h"h"http://www.w3.org/1999/xhtml"ttp://www.w3.org/1999/xhtml"ttp://www.w3.org/1999/xhtml"ttp://www.w3.org/1999/xhtml">>>>
8 <head> <head> <head> <head>
9 <title><title><title><title>Using arithmetic opeUsing arithmetic opeUsing arithmetic opeUsing arithmetic operarararatorstorstorstors</title></title></title></title>
10 </head> </head> </head> </head>
11
12 <body> <body> <body> <body>
13 <?php<?php<?php<?php
14 $a = $a = $a = $a = 5555;;;;
15 printprintprintprint( ( ( ( "The value of variable a is $a <br />""The value of variable a is $a <br />""The value of variable a is $a <br />""The value of variable a is $a <br />" ); ); ); );
16
17 // define constant VALUE// define constant VALUE// define constant VALUE// define constant VALUE
18 define( define( define( define( "VALUE""VALUE""VALUE""VALUE", , , , 5555 ); ); ); );
19
20 // add constant VALUE to variable $a// add constant VALUE to variable $a// add constant VALUE to variable $a// add constant VALUE to variable $a
21 $a = $a + $a = $a + $a = $a + $a = $a + VALUEVALUEVALUEVALUE;;;;
22 printprintprintprint( ( ( ( "Variable a after adding constant VALUE "Variable a after adding constant VALUE "Variable a after adding constant VALUE "Variable a after adding constant VALUE
23 isisisis $a <br />" $a <br />" $a <br />" $a <br />" ); ); ); );
24
operators.php
(1 of 3)
Define constant VALUE.
Add constant VALUE to variable $a.
2003 Prentice Hall, Inc.
All rights reserved.
Outline15
25 // multiply variable $a by 2// multiply variable $a by 2// multiply variable $a by 2// multiply variable $a by 2
26 $a *= $a *= $a *= $a *= 2222;;;;
27 printprintprintprint( ( ( ( "Multiplying variable a by 2 yields $a <br />""Multiplying variable a by 2 yields $a <br />""Multiplying variable a by 2 yields $a <br />""Multiplying variable a by 2 yields $a <br />" ); ); ); );
28
29 // test if variable $a is less than 50// test if variable $a is less than 50// test if variable $a is less than 50// test if variable $a is less than 50
30 if if if if ( $a < ( $a < ( $a < ( $a < 50505050 ) ) ) )
31 prprprprintintintint( ( ( ( "Variable a is less than 50 <br />""Variable a is less than 50 <br />""Variable a is less than 50 <br />""Variable a is less than 50 <br />" ); ); ); );
32
33 // add 40 to variable $a // add 40 to variable $a // add 40 to variable $a // add 40 to variable $a
34 $a += $a += $a += $a += 40404040;;;;
35 printprintprintprint( ( ( ( "Variable a after adding 40 is $a <br />""Variable a after adding 40 is $a <br />""Variable a after adding 40 is $a <br />""Variable a after adding 40 is $a <br />" ); ); ); );
36
37 // test if variable $a is 50 or less// test if variable $a is 50 or less// test if variable $a is 50 or less// test if variable $a is 50 or less
38 ifififif ( $a < ( $a < ( $a < ( $a < 51515151 ) ) ) )
39 printprintprintprint( ( ( ( "Variable a is still 50 or less<br />""Variable a is still 50 or less<br />""Variable a is still 50 or less<br />""Variable a is still 50 or less<br />" ); ); ); );
40
41 // test if variable $a is between 50 and 100, inclusive// test if variable $a is between 50 and 100, inclusive// test if variable $a is between 50 and 100, inclusive// test if variable $a is between 50 and 100, inclusive
42 elseifelseifelseifelseif ( $a < ( $a < ( $a < ( $a < 101101101101 ) ) ) )
43 printprintprintprint( ( ( ( "Variable a is now between 50 "Variable a is now between 50 "Variable a is now between 50 "Variable a is now between 50 and 100, and 100, and 100, and 100,
44 inclusive<br />"inclusive<br />"inclusive<br />"inclusive<br />" ); ); ); );
45 elseelseelseelse
46 printprintprintprint( ( ( ( "Variable a is now greater than 100"Variable a is now greater than 100"Variable a is now greater than 100"Variable a is now greater than 100
47 <br />"<br />"<br />"<br />" ); ); ); );
48
operators.php
(2 of 3)
Multiply variable $a by two using the
multiplication assignment operator *=.
Test whether variable $a is less than 50
Add 40 to variable $a using the addition assignment operator +=.
Print if variable $a is less than 50.
2003 Prentice Hall, Inc.
All rights reserved.
Outline16
49 // print an uninitialized variable // print an uninitialized variable // print an uninitialized variable // print an uninitialized variable
50 printprintprintprint( ( ( ( "Using a variable before initializing:"Using a variable before initializing:"Using a variable before initializing:"Using a variable before initializing:
51 $nothing <br />"$nothing <br />"$nothing <br />"$nothing <br />" ); ); ); );
52
53 // add constant VALUE to an uninitialized variable// add constant VALUE to an uninitialized variable// add constant VALUE to an uninitialized variable// add constant VALUE to an uninitialized variable
54 $test = $num + $test = $num + $test = $num + $test = $num + VALUVALUVALUVALUEEEE;;;;
55 print print print print( ( ( ( "An uninitialized variable plus constant"An uninitialized variable plus constant"An uninitialized variable plus constant"An uninitialized variable plus constant
56 VALUE yields $test <br />"VALUE yields $test <br />"VALUE yields $test <br />"VALUE yields $test <br />" ); ); ); );
57
58 // add a string to an integer// add a string to an integer// add a string to an integer// add a string to an integer
59 $str = $str = $str = $str = "3 dollars""3 dollars""3 dollars""3 dollars";;;;
60 $a += $str;$a += $str;$a += $str;$a += $str;
61 prin prin prin printttt( ( ( ( "Adding a string to "Adding a string to "Adding a string to "Adding a string to variable avariable avariable avariable a yields $a yields $a yields $a yields $a
62 <br />"<br />"<br />"<br />" ); ); ); );
63 ?>?>?>?>
64 </body> </body> </body> </body>
65 </html></html></html></html>
operators.php
(3 of 3)
Add constant VALUE to an uninitialized
variable.
Add a string to an integer.
Print an uninitialized variable ($nothing).
2003 Prentice Hall, Inc. All rights reserved.
17
26.2 PHPFig. 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 break case class continue default
do else elseif extends false
for foreach function global if
include list new not or
require return static switch this
true var virtual xor while
Fig. 26.5 PHP keywords.
2003 Prentice Hall, Inc.
All rights reserved.
Outline211 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.6: arrays.php Fig. 26.6: arrays.php Fig. 26.6: arrays.php Fig. 26.6: arrays.php -------->>>>
5 <!<!<!<!-------- Array manipulation Array manipulation Array manipulation Array manipulation -------->>>>
6
7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www."http://www."http://www."http://www.w3.org/1999/xhtml"w3.org/1999/xhtml"w3.org/1999/xhtml"w3.org/1999/xhtml">>>>
8 <head><head><head><head>
9 <title><title><title><title>Array manipulationArray manipulationArray manipulationArray manipulation</title></title></title></title>
10 </head> </head> </head> </head>
11
12 <body> <body> <body> <body>
13 <?php<?php<?php<?php
14
15 // create array first// create array first// create array first// create array first
16 printprintprintprint( ( ( ( "<strong>Creating the first array</strong>"<strong>Creating the first array</strong>"<strong>Creating the first array</strong>"<strong>Creating the first array</strong>
17 <br />"<br />"<br />"<br />" ); ); ); );
18 $first[ $first[ $first[ $first[ 0000 ] = ] = ] = ] = "zero""zero""zero""zero";;;;
19 $first[ $first[ $first[ $first[ 1111 ] = ] = ] = ] = "one""one""one""one";;;;
20 $first[ $first[ $first[ $first[ 2222 ] = ] = ] = ] = "two""two""two""two";;;;
21 $first[] = $first[] = $first[] = $first[] = "three""three""three""three";;;;
22
23 // print each element’s index and value // print each element’s index and value // print each element’s index and value // print each element’s index and value
24 for for for for ( $i =( $i =( $i =( $i = 0000; $i < ; $i < ; $i < ; $i < countcountcountcount( $first )( $first )( $first )( $first ); $i++ ) ; $i++ ) ; $i++ ) ; $i++ )
25 printprintprintprint( ( ( ( "Element $i is $first[$i] <br />""Element $i is $first[$i] <br />""Element $i is $first[$i] <br />""Element $i is $first[$i] <br />" ); ); ); );
arrays.php
(1 of 3)
Create the array $first by assigning a value
to an array element.
Assign a value to the array, omitting the index.
Appends a new element to the end of the array.Use a for loop to print out each element’s index and value.
Function count returns the total number of elements in the
array.
2003 Prentice Hall, Inc.
All rights reserved.
Outline22
26
27 printprintprintprint( ( ( ( "<br /><strong>Creating the second array"<br /><strong>Creating the second array"<br /><strong>Creating the second array"<br /><strong>Creating the second array
28 </strong><br />"</strong><br />"</strong><br />"</strong><br />" ); ); ); );
29
30 // call function array to create array second // call function array to create array second // call function array to create array second // call function array to create array second
31 $second = $second = $second = $second = array( array( array( array( "zero""zero""zero""zero", , , , "one""one""one""one", , , , "two""two""two""two", , , , "three""three""three""three" ); ); ); );
32 for for for for ( $i = ( $i = ( $i = ( $i = 0000; $i < count( $second ); $i++ ) ; $i < count( $second ); $i++ ) ; $i < count( $second ); $i++ ) ; $i < count( $second ); $i++ )
33 printprintprintprint( ( ( ( "Element $i is $second[$i] <br />""Element $i is $second[$i] <br />""Element $i is $second[$i] <br />""Element $i is $second[$i] <br />" ); ); ); );
34
35 printprintprintprint( ( ( ( "<br /><strong>Creating the third array"<br /><strong>Creating the third array"<br /><strong>Creating the third array"<br /><strong>Creating the third array
36 </strong><br />"</strong><br />"</strong><br />"</strong><br />" ); ); ); );
37
38 // assign val// assign val// assign val// assign values to nonues to nonues to nonues to non----numerical indices numerical indices numerical indices numerical indices
39 $third[ $third[ $third[ $third[ "ArtTic""ArtTic""ArtTic""ArtTic" ] = ] = ] = ] = 21212121;;;;
40 $third[ $third[ $third[ $third[ "LunaTic""LunaTic""LunaTic""LunaTic" ] = ] = ] = ] = 18181818;;;;
41 $third[ $third[ $third[ $third[ "GalAnt""GalAnt""GalAnt""GalAnt" ] = ] = ] = ] = 23232323;;;;
42
43 // iterate through the array elements and print each // iterate through the array elements and print each // iterate through the array elements and print each // iterate through the array elements and print each
44 // element’s n // element’s n // element’s n // element’s name and valueame and valueame and valueame and value
45 for for for for ( reset( $third ); $element = key( $third );( reset( $third ); $element = key( $third );( reset( $third ); $element = key( $third );( reset( $third ); $element = key( $third );
46 next( $third ) )next( $third ) )next( $third ) )next( $third ) )
47 printprintprintprint( ( ( ( "$element is $third[$element] <br />""$element is $third[$element] <br />""$element is $third[$element] <br />""$element is $third[$element] <br />" ); ); ); );
48
arrays.php
(2 of 3)
Call function array to create an array that contains
the arguments passed to it. Store the array in variable
$second.
Assign values to non-numerical indices
in array $third.Function reset sets the internal pointer to the
first element of the array.
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.
Outline23
49 printprintprintprint( ( ( ( "<br /><strong>Creating the fourth array"<br /><strong>Creating the fourth array"<br /><strong>Creating the fourth array"<br /><strong>Creating the fourth array
50 </strong><br />"</strong><br />"</strong><br />"</strong><br />" ); ); ); );
51
52 // call function array to create array fourth using // call function array to create array fourth using // call function array to create array fourth using // call function array to create array fourth using
53 // string indices // string indices // string indices // string indices
54 $fourth = array( $fourth = array( $fourth = array( $fourth = array(
55 "January""January""January""January" => => => => "first""first""first""first", , , , "February""February""February""February" => => => => "second""second""second""second",,,,
56 "March""March""March""March" => => => => "third""third""third""third", , , , "April""April""April""April" => => => => "fourth""fourth""fourth""fourth",,,,
57 "May""May""May""May" => => => => "fifth""fifth""fifth""fifth", , , , "June""June""June""June" => => => => "sixth""sixth""sixth""sixth",,,,
58 "July""July""July""July" => => => => "seventh""seventh""seventh""seventh", , , , "August""August""August""August" => => => => "eighth""eighth""eighth""eighth",,,,
59 "September""September""September""September" => => => => "ninth""ninth""ninth""ninth", , , , "October""October""October""October" => => => => "tenth""tenth""tenth""tenth",,,,
60 "November""November""November""November" => => => => "eleventh""eleventh""eleventh""eleventh",,,,"December""December""December""December" => => => => "twelfth""twelfth""twelfth""twelfth"
61 ); ); ); );
62
63 // print each element’s name and value // print each element’s name and value // print each element’s name and value // print each element’s name and value
64 foreach foreach foreach foreach ( $fourth as $el( $fourth as $el( $fourth as $el( $fourth as $element => $value )ement => $value )ement => $value )ement => $value )
65 printprintprintprint( ( ( ( "$element is the $value month <br />""$element is the $value month <br />""$element is the $value month <br />""$element is the $value month <br />" ); ); ); );
66 ?>?>?>?>
67 </body> </body> </body> </body>
68 </html></html></html></html>
arrays.php
(3 of 3)
Operator => is used in function array to assign each
element a string index. The value to the left of the
operator is the array index, and the value to the right is
the element’s value.
2003 Prentice Hall, Inc. All rights reserved.
24
26.2 PHPFig. 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.
Outline261 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.7: compare.php Fig. 26.7: compare.php Fig. 26.7: compare.php Fig. 26.7: compare.php -------->>>>
5 <!<!<!<!-------- String Comparison String Comparison String Comparison String Comparison -------->>>>
6
7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://ww"http://ww"http://ww"http://www.w3.org/1999/xhtml"w.w3.org/1999/xhtml"w.w3.org/1999/xhtml"w.w3.org/1999/xhtml">>>>
8 <head> <head> <head> <head>
9 <title><title><title><title>String ComparisonString ComparisonString ComparisonString Comparison</title></title></title></title>
10 </head> </head> </head> </head>
11
12 <body> <body> <body> <body>
13 <?php <?php <?php <?php
14
15 // create array fruits// create array fruits// create array fruits// create array fruits
16 $fruits = array( $fruits = array( $fruits = array( $fruits = array( "apple""apple""apple""apple", , , , "orange""orange""orange""orange", , , , "banana""banana""banana""banana" ); ); ); );
17
18 // iterate through each array element// iterate through each array element// iterate through each array element// iterate through each array element
19 forforforfor ( $i = ( $i = ( $i = ( $i = 0000; $i < count( $fruits ); $i++ ) {; $i < count( $fruits ); $i++ ) {; $i < count( $fruits ); $i++ ) {; $i < count( $fruits ); $i++ ) {
20
21 // call function strcmp to compare the array element // call function strcmp to compare the array element // call function strcmp to compare the array element // call function strcmp to compare the array element
22 // to string "banana" // to string "banana" // to string "banana" // to string "banana"
23 ifififif ( ( ( ( strcmp( $fruits[ $i ], strcmp( $fruits[ $i ], strcmp( $fruits[ $i ], strcmp( $fruits[ $i ], "banana""banana""banana""banana" ) ) ) ) < < < < 0000 ) ) ) )
24 printprintprintprint( $fruits[ $i ].( $fruits[ $i ].( $fruits[ $i ].( $fruits[ $i ]." is less than banana "" is less than banana "" is less than banana "" is less than banana " ); ); ); );
compare.php
(1 of 2)
Use a for loop to iterate through each array element.
Function strcmp compares two strings. If the first string
alphabetically precedes the second, then –1 is returned. If
the strings are equal, 0 is returned. If the first string
alphabetically follows the second, then 1 is returned.
2003 Prentice Hall, Inc.
All rights reserved.
Outline27
25 elseifelseifelseifelseif ( strcmp( $fruits[ $i ], ( strcmp( $fruits[ $i ], ( strcmp( $fruits[ $i ], ( strcmp( $fruits[ $i ], "banana""banana""banana""banana" ) > ) > ) > ) > 0000 ) ) ) )
26 printprintprintprint( $fruits[ $i ].( $fruits[ $i ].( $fruits[ $i ].( $fruits[ $i ].
27 " is greater than banana "" is greater than banana "" is greater than banana "" is greater than banana " ); ); ); );
28 elseelseelseelse
29 printprintprintprint( $fruits[ $i ].( $fruits[ $i ].( $fruits[ $i ].( $fruits[ $i ]." is equal to banana "" is equal to banana "" is equal to banana "" is equal to banana " ); ); ); );
30
31 // use relational operators to compare each element // use relational operators to compare each element // use relational operators to compare each element // use relational operators to compare each element
32 // to string "apple" // to string "apple" // to string "apple" // to string "apple"
33 ifififif ( $fruits[ $i ] < ( $fruits[ $i ] < ( $fruits[ $i ] < ( $fruits[ $i ] < "apple""apple""apple""apple" ) ) ) )
34 print print print print( ( ( ( "and less than apple! <br />""and less than apple! <br />""and less than apple! <br />""and less than apple! <br />" ); ); ); );
35 elseifelseifelseifelseif ( $fruits[ $i ] > ( $fruits[ $i ] > ( $fruits[ $i ] > ( $fruits[ $i ] > "apple""apple""apple""apple" ) ) ) )
36 print print print print( ( ( ( "and greater than apple! <br />""and greater than apple! <br />""and greater than apple! <br />""and greater than apple! <br />" ); ); ); );
37 elseifelseifelseifelseif ( $fruits[ $i ] == ( $fruits[ $i ] == ( $fruits[ $i ] == ( $fruits[ $i ] == "apple""apple""apple""apple" ) ) ) )
38 print print print print( ( ( ( "and equal to apple! <br />""and equal to apple! <br />""and equal to apple! <br />""and equal to apple! <br />" ); ); ); );
39
40 }}}}
41 ?>?>?>?>
42 </body> </body> </body> </body>
43 </html></html></html></html>
compare.php
(2 of 2)
Use relational operators to compare each array element to string “apple”.
2003 Prentice Hall, Inc. All rights reserved.
28
26.3 String Processing and Regular
ExpressionsFig. 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.
Outline301 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.8: expression.php Fig. 26.8: expression.php Fig. 26.8: expression.php Fig. 26.8: expression.php -------->>>>
5 <!<!<!<!-------- Using regular expressions Using regular expressions Using regular expressions Using regular expressions -------->>>>
6
7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "htt"htt"htt"http://www.w3.org/1999/xhtml"p://www.w3.org/1999/xhtml"p://www.w3.org/1999/xhtml"p://www.w3.org/1999/xhtml">>>>
8 <head> <head> <head> <head>
9 <title> <title> <title> <title>Regular expressionsRegular expressionsRegular expressionsRegular expressions</title></title></title></title>
10 </head> </head> </head> </head>
11
12 <body> <body> <body> <body>
13 <?php<?php<?php<?php
14 $search = $search = $search = $search = "Now is the time""Now is the time""Now is the time""Now is the time";;;;
15 print print print print( ( ( ( "Test string is: '$search'<br /><br />""Test string is: '$search'<br /><br />""Test string is: '$search'<br /><br />""Test string is: '$search'<br /><br />" ) ) ) );;;;
16
17 // call function ereg to search for pattern 'Now' // call function ereg to search for pattern 'Now' // call function ereg to search for pattern 'Now' // call function ereg to search for pattern 'Now'
18 // in variable search // in variable search // in variable search // in variable search
19 if if if if ( ( ( ( ereg( ereg( ereg( ereg( "Now""Now""Now""Now", $search ), $search ), $search ), $search ) ) ) ) )
20 print print print print( ( ( ( "String 'Now' was found.<br />""String 'Now' was found.<br />""String 'Now' was found.<br />""String 'Now' was found.<br />" ); ); ); );
21
expression.php
(1 of 3)
Function ereg searches for the literal
characters Now inside variable $search.
2003 Prentice Hall, Inc.
All rights reserved.
Outline31
22 // search for pattern 'Now' in the beginning of // search for pattern 'Now' in the beginning of // search for pattern 'Now' in the beginning of // search for pattern 'Now' in the beginning of
23 // the string // the string // the string // the string
24 if if if if ( ( ( ( ereg( ereg( ereg( ereg( "^Now""^Now""^Now""^Now", $search ), $search ), $search ), $search ) ) ) ) )
25 print print print print( ( ( ( "String 'Now' found at beginning"String 'Now' found at beginning"String 'Now' found at beginning"String 'Now' found at beginning
26 of the line.<br />"of the line.<br />"of the line.<br />"of the line.<br />" ); ); ); );
27
28 // search for pattern 'Now' at the end of the string // search for pattern 'Now' at the end of the string // search for pattern 'Now' at the end of the string // search for pattern 'Now' at the end of the string
29 if if if if ( ( ( ( ereg( ereg( ereg( ereg( "Now$""Now$""Now$""Now$", $search ), $search ), $search ), $search ) ) ) ) )
30 print print print print( ( ( ( "String 'Now' was found at the end "String 'Now' was found at the end "String 'Now' was found at the end "String 'Now' was found at the end
31 of the line.<br />"of the line.<br />"of the line.<br />"of the line.<br />" ); ); ); );
32
33 // search for any word ending in 'ow'// search for any word ending in 'ow'// search for any word ending in 'ow'// search for any word ending in 'ow'
34 ifififif ( ereg( ( ereg( ( ereg( ( ereg( "[[:<:]]([a"[[:<:]]([a"[[:<:]]([a"[[:<:]]([a----zAzAzAzA----Z]*ow)[[:>:]]"Z]*ow)[[:>:]]"Z]*ow)[[:>:]]"Z]*ow)[[:>:]]", $search,, $search,, $search,, $search,
35 $match ) )$match ) )$match ) )$match ) )
36 printprintprintprint( ( ( ( "Word found ending in 'ow': ""Word found ending in 'ow': ""Word found ending in 'ow': ""Word found ending in 'ow': " . . . .
37 $mat$mat$mat$match[ ch[ ch[ ch[ 1111 ] ] ] ] . . . . "<br />""<br />""<br />""<br />" ); ); ); );
38
39 // search for any words beginning with 't' // search for any words beginning with 't' // search for any words beginning with 't' // search for any words beginning with 't'
40 print print print print( ( ( ( "Words beginning with 't' found: ""Words beginning with 't' found: ""Words beginning with 't' found: ""Words beginning with 't' found: "););););
41
42 whilewhilewhilewhile ( eregi( ( eregi( ( eregi( ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]""[[:<:]](t[[:alpha:]]+)[[:>:]]""[[:<:]](t[[:alpha:]]+)[[:>:]]""[[:<:]](t[[:alpha:]]+)[[:>:]]",,,,
43 $search, $$search, $$search, $$search, $match ) )match ) )match ) )match ) ) { { { {
44 print print print print( $match[ ( $match[ ( $match[ ( $match[ 1111 ] . ] . ] . ] . " "" "" "" " ); ); ); );
45
expression.php
(2 of 3)
The dollar sign special character ($) search for the
pattern Now at the end of the string.
The expression inside the parentheses, [a-zA-Z]*ow,
matches any word ending in ow. The quantifier *
matches the preceding pattern 0 or more times.
The special bracket expressions [[:<:]] and
[[:>:]] match the beginning and end of a
word, respectively.
Placing a pattern in parentheses stores the matched
string in the array that is specified in the third argument
to function ereg.
The while loop is used to find each occurrence of a
word in the string beginning with t.
The pattern used in this example,
[[:<:]](t[[:alpha:]]+)[[:>:]], matches any
word beginning with the character t followed by one or
more characters. Character class [[:alpha:]]
recognizes any alphabetic character.
Function eregi is used to specify case insensitive
pattern matches.
The caret special character (^) matches the
beginning of a string. Function ereg searches the
beginning of the string for pattern Now .
2003 Prentice Hall, Inc.
All rights reserved.
Outline32
expression.php
(3 of 3)
46 // remove the first occurrence of a word beginning // remove the first occurrence of a word beginning // remove the first occurrence of a word beginning // remove the first occurrence of a word beginning
47 // with 't' to find other instances in the string // with 't' to find other instances in the string // with 't' to find other instances in the string // with 't' to find other instances in the string
48 $search = ereg_replace( $match[ $search = ereg_replace( $match[ $search = ereg_replace( $match[ $search = ereg_replace( $match[ 1111 ], ], ], ], """""""", $search );, $search );, $search );, $search );
49 } } } }
50
51 print print print print( ( ( ( "<b"<b"<b"<br />"r />"r />"r />" ); ); ); );
52 ?>?>?>?>
53 </body> </body> </body> </body>
54 </html></html></html></html>
After printing a match of a word beginning with t, function
ereg_replace is called to remove the word from the string.
This is necessary be because to find multiple instances of a
given pattern, the first matched instance must first be removed.
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
ExpressionsFig. 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.
Outline381 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.11: env.php Fig. 26.11: env.php Fig. 26.11: env.php Fig. 26.11: env.php -------->>>>
5 <!<!<!<!-------- Program to display environment variables Program to display environment variables Program to display environment variables Program to display environment variables -------->>>>
6
7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>
8 <head> <head> <head> <head>
9 <title> <title> <title> <title>Environment VariablesEnvironment VariablesEnvironment VariablesEnvironment Variables</title></title></title></title>
10 </head> </head> </head> </head>
11
12 <body> <body> <body> <body>
13 <table border = <table border = <table border = <table border = "0""0""0""0" cellpadding = cellpadding = cellpadding = cellpadding = "2""2""2""2" cellspacing = cellspacing = cellspacing = cellspacing = "0""0""0""0"
14 width = width = width = width = "1"1"1"100%"00%"00%"00%">>>>
15 <?php<?php<?php<?php
16
17 // print the key and value for each element // print the key and value for each element // print the key and value for each element // print the key and value for each element
18 // in the $_ENV array // in the $_ENV array // in the $_ENV array // in the $_ENV array
19 foreachforeachforeachforeach ( $_ENV ( $_ENV ( $_ENV ( $_ENV asasasas $key => $value ) $key => $value ) $key => $value ) $key => $value )
20 printprintprintprint( ( ( ( "<tr><td bgcolor = "<tr><td bgcolor = "<tr><td bgcolor = "<tr><td bgcolor = \\\\"#11bbff"#11bbff"#11bbff"#11bbff\\\\">">">">
21 <strong>$key</strong></td><strong>$key</strong></td><strong>$key</strong></td><strong>$key</strong></td>
22 <td>$value</td></tr>"<td>$value</td></tr>"<td>$value</td></tr>"<td>$value</td></tr>" ); ); ); );
23 ?>?>?>?>
24 </table> </table> </table> </table>
25 </body> </body> </body> </body>
26 </html></html></html></html>
env.php
(1 of 1)
The foreach loop is used to print out the keys and
values for each element in the $_ENV array.PHP stores environment variables and their values in
the $_ENV array.
2003 Prentice Hall, Inc. All rights reserved.
39
26.4 Viewing Client/Server Environment
VariablesFig. 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.
Outline411 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.13: form.html Fig. 26.13: form.html Fig. 26.13: form.html Fig. 26.13: form.html --------> > > >
5 <!<!<!<!-------- Form for use with the form.php program Form for use with the form.php program Form for use with the form.php program Form for use with the form.php program -------->>>>
6
7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>
8 <head> <head> <head> <head>
9 <title> <title> <title> <title>Sample form to take user input in XHTMLSample form to take user input in XHTMLSample form to take user input in XHTMLSample form to take user input in XHTML</title></title></title></title>
10 </head> </head> </head> </head>
11
12 <body> <body> <body> <body>
13
14 <h1> <h1> <h1> <h1>This is a sample registration form.This is a sample registration form.This is a sample registration form.This is a sample registration form.</h1></h1></h1></h1>
15 Please fill in all fields and click Register.Please fill in all fields and click Register.Please fill in all fields and click Register.Please fill in all fields and click Register.
16
17 <!<!<!<!-------- post form data to form.php post form data to form.php post form data to form.php post form data to form.php -------->>>>
18 <form method = <form method = <form method = <form method = "post""post""post""post" action = action = action = action = "form.php""form.php""form.php""form.php">>>>
19 <img src = <img src = <img src = <img src = "images/user.gif""images/user.gif""images/user.gif""images/user.gif" alt = alt = alt = alt = "User" "User" "User" "User" /><br />/><br />/><br />/><br />
20 <span style = <span style = <span style = <span style = """"color: blue"color: blue"color: blue"color: blue">>>>
21 Please fill out the fields below. Please fill out the fields below. Please fill out the fields below. Please fill out the fields below.<br /><br /><br /><br />
22 </span> </span> </span> </span>
23
form.html
(1 of 4)
The action attribute of the form element
indicates that when the user clicks Register, the
form data will be posted to form.php.
2003 Prentice Hall, Inc.
All rights reserved.
Outline42
24 <! <! <! <!-------- create four text boxes for user input create four text boxes for user input create four text boxes for user input create four text boxes for user input -------->>>>
25 <img src = <img src = <img src = <img src = "images/fname.gif""images/fname.gif""images/fname.gif""images/fname.gif" alt = alt = alt = alt = "First Name""First Name""First Name""First Name" /> /> /> />
26 <input type = <input type = <input type = <input type = "text""text""text""text" name = name = name = name = "fname""fname""fname""fname" /><br /> /><br /> /><br /> /><br />
27
28 <img src = <img src = <img src = <img src = "images/lname.gif""images/lname.gif""images/lname.gif""images/lname.gif" alt = alt = alt = alt = "La"La"La"Last Name" st Name" st Name" st Name" />/>/>/>
29 <input type = <input type = <input type = <input type = "text""text""text""text" name = name = name = name = "lname""lname""lname""lname" /><br /> /><br /> /><br /> /><br />
30
31 <img src = <img src = <img src = <img src = "images/email.gif""images/email.gif""images/email.gif""images/email.gif" alt = alt = alt = alt = "Email" "Email" "Email" "Email" /> /> /> />
32 <input type = <input type = <input type = <input type = "text""text""text""text" name = name = name = name = "email""email""email""email" /><br /> /><br /> /><br /> /><br />
33
34 <img src = <img src = <img src = <img src = "images/p"images/p"images/p"images/phone.gif"hone.gif"hone.gif"hone.gif" alt = alt = alt = alt = "Phone" "Phone" "Phone" "Phone" /> /> /> />
35 <input type = <input type = <input type = <input type = "text""text""text""text" name = name = name = name = "phone""phone""phone""phone" /><br /> /><br /> /><br /> /><br />
36
37 <span style = <span style = <span style = <span style = "font"font"font"font----size: 10pt"size: 10pt"size: 10pt"size: 10pt">>>>
38 Must be in the form (555)555 Must be in the form (555)555 Must be in the form (555)555 Must be in the form (555)555----5555555555555555</span></span></span></span>
39 <br /><br /> <br /><br /> <br /><br /> <br /><br />
40
41 <img src = <img src = <img src = <img src = "images/downloads.gif""images/downloads.gif""images/downloads.gif""images/downloads.gif"
42 alt = alt = alt = alt = "Publications" "Publications" "Publications" "Publications" /><br />/><br />/><br />/><br />
43
44 <span style = <span style = <span style = <span style = "color: blue""color: blue""color: blue""color: blue">>>>
45 Which book would you like information about? Which book would you like information about? Which book would you like information about? Which book would you like information about?
46 </span><br /> </span><br /> </span><br /> </span><br />
47
form.html
(2 of 4)
A unique name (e.g., email) is assigned to each
of the form’s input fields. When Register is
clicked, each field’s name and value are sent to
the Web server.
2003 Prentice Hall, Inc.
All rights reserved.
Outline43
48 <! <! <! <!-------- create drop create drop create drop create drop----down list containing book names down list containing book names down list containing book names down list containing book names -------->>>>
49 <select name = <select name = <select name = <select name = "book""book""book""book">>>>
50 <option><option><option><option>Internet and WWW How to Program 3eInternet and WWW How to Program 3eInternet and WWW How to Program 3eInternet and WWW How to Program 3e</option></option></option></option>
51 <option><option><option><option>C++ How to Program 4eC++ How to Program 4eC++ How to Program 4eC++ How to Program 4e</option></option></option></option>
52 <optio <optio <optio <option>n>n>n>Java How to Program 5eJava How to Program 5eJava How to Program 5eJava How to Program 5e</option></option></option></option>
53 <option> <option> <option> <option>XML How to Program 1eXML How to Program 1eXML How to Program 1eXML How to Program 1e</option></option></option></option>
54 </select> </select> </select> </select>
55 <br /><br /> <br /><br /> <br /><br /> <br /><br />
56
57 <img src = <img src = <img src = <img src = "images/os.gif""images/os.gif""images/os.gif""images/os.gif" alt = alt = alt = alt = "Operating System" "Operating System" "Operating System" "Operating System" />/>/>/>
58 <br /><span style = <br /><span style = <br /><span style = <br /><span style = "color: blue""color: blue""color: blue""color: blue">>>>
59 Which operating system are you currently using? Which operating system are you currently using? Which operating system are you currently using? Which operating system are you currently using?
60 <br /></span> <br /></span> <br /></span> <br /></span>
61
62 <! <! <! <!-------- create five radio buttons create five radio buttons create five radio buttons create five radio buttons -------->>>>
63 <input type = <input type = <input type = <input type = "radio""radio""radio""radio" name = name = name = name = "os""os""os""os" value = value = value = value = "Windows XP""Windows XP""Windows XP""Windows XP"
64 cccchecked = hecked = hecked = hecked = "checked""checked""checked""checked" /> /> /> />
65 Windows XP Windows XP Windows XP Windows XP
66
67 <input type = <input type = <input type = <input type = "radio" "radio" "radio" "radio" name = name = name = name = "os""os""os""os" value = value = value = value =
68 "Windows 2000" "Windows 2000" "Windows 2000" "Windows 2000" /> /> /> />
69 Windows 2000Windows 2000Windows 2000Windows 2000
70
71 <input ty <input ty <input ty <input type = pe = pe = pe = "radio""radio""radio""radio" name = name = name = name = "os""os""os""os" value = value = value = value =
72 "Windows 98" "Windows 98" "Windows 98" "Windows 98" /> /> /> />
73 Windows 98Windows 98Windows 98Windows 98<br /><br /><br /><br />
form.html
(3 of 4)
2003 Prentice Hall, Inc.
All rights reserved.
Outline44
form.html
(4 of 4)
74
75 <input type = <input type = <input type = <input type = "radio""radio""radio""radio" name = name = name = name = "os""os""os""os" value = value = value = value = "Linux""Linux""Linux""Linux" /> /> /> />
76 LinuxLinuxLinuxLinux
77
78 <input type = <input type = <input type = <input type = "radio""radio""radio""radio" name = name = name = name = "os""os""os""os" value = value = value = value = "Other""Other""Other""Other" /> /> /> />
79 Other Other Other Other<br /><br /><br /><br />
80
81 <! <! <! <!-------- create a su create a su create a su create a submit button bmit button bmit button bmit button -------->>>>
82 <input type = <input type = <input type = <input type = "submit""submit""submit""submit" value = value = value = value = "Register""Register""Register""Register" /> /> /> />
83 </form> </form> </form> </form>
84
85 </body> </body> </body> </body>
86 </html></html></html></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.
Outline471 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.14: form.php Fig. 26.14: form.php Fig. 26.14: form.php Fig. 26.14: form.php -------->>>>
5 <!<!<!<!-------- Read information sent from form.html Read information sent from form.html Read information sent from form.html Read information sent from form.html -------->>>>
6
7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>
8 <head> <head> <head> <head>
9 <title> <title> <title> <title>Form ValidationForm ValidationForm ValidationForm Validation</title></title></title></title>
10 </head> </head> </head> </head>
11
12 <body style = <body style = <body style = <body style = "font"font"font"font----family: arial,sansfamily: arial,sansfamily: arial,sansfamily: arial,sans----serif"serif"serif"serif">>>>
13
14 <?php<?php<?php<?php
15 extract( $_POST );extract( $_POST );extract( $_POST );extract( $_POST );
16
17 // determine whether phone number is valid and print // determine whether phone number is valid and print // determine whether phone number is valid and print // determine whether phone number is valid and print
18 // an error message if not // an error message if not // an error message if not // an error message if not
19 ifififif ( !ereg( ( !ereg( ( !ereg( ( !ereg( "^"^"^"^\\\\([0([0([0([0----9]{3}9]{3}9]{3}9]{3}\\\\)[0)[0)[0)[0----9]{3}9]{3}9]{3}9]{3}----[0[0[0[0----9]{4}$"9]{4}$"9]{4}$"9]{4}$",,,,
20 $phone ) ){$phone ) ){$phone ) ){$phone ) ){
21
form.php
(1 of 4)
Function ereg is called to determine whether the
phone number entered by the user is valid. The expression \( matches the opening
parentheses of a phone number.
We access the phone field’s value from
form.html by using variable $phone.
The parentheses in the expression must be
followed by three digits ([0-9]{3}), a closing
parenthesis, three digits, a literal hyphen and
four additional digits.
2003 Prentice Hall, Inc.
All rights reserved.
Outline48
22 printprintprintprint( ( ( ( "<p><span style = "<p><span style = "<p><span style = "<p><span style = \\\\"color: red;"color: red;"color: red;"color: red;
23 font font font font----size: 2emsize: 2emsize: 2emsize: 2em\\\\">">">">
24 INVALID PHONE NUMBER</span><br /> INVALID PHONE NUMBER</span><br /> INVALID PHONE NUMBER</span><br /> INVALID PHONE NUMBER</span><br />
25 A valid phone number must be in the form A valid phone number must be in the form A valid phone number must be in the form A valid phone number must be in the form
26 <strong>(555)555 <strong>(555)555 <strong>(555)555 <strong>(555)555----5555<5555<5555<5555</strong><br />/strong><br />/strong><br />/strong><br />
27 <span style = <span style = <span style = <span style = \\\\"color: blue"color: blue"color: blue"color: blue\\\\"> "> "> ">
28 Click the Back button, enter a valid phone Click the Back button, enter a valid phone Click the Back button, enter a valid phone Click the Back button, enter a valid phone
29 number and resubmit.<br /><br /> number and resubmit.<br /><br /> number and resubmit.<br /><br /> number and resubmit.<br /><br />
30 Thank You.</span></p></body></html>"Thank You.</span></p></body></html>"Thank You.</span></p></body></html>"Thank You.</span></p></body></html>" ); ); ); );
31
32 die();die();die();die(); // terminate script execution// terminate script execution// terminate script execution// terminate script execution
33 } } } }
34 ?>?>?>?>
35
36 <p> <p> <p> <p>Hi Hi Hi Hi
37 <span style = <span style = <span style = <span style = "color: blue""color: blue""color: blue""color: blue">>>>
38 <strong> <strong> <strong> <strong>
39 <?php <?php <?php <?php printprintprintprint( ( ( ( "$fname""$fname""$fname""$fname" ); ); ); ); ?>?>?>?>
40 </stro </stro </stro </strong>ng>ng>ng>
41 </span> </span> </span> </span>....
42 Thank you for completing the survey.Thank you for completing the survey.Thank you for completing the survey.Thank you for completing the survey.<br /><br /><br /><br />
43
form.php
(2 of 4)
Function die terminates script execution
2003 Prentice Hall, Inc.
All rights reserved.
Outline49
44 You have been added to the You have been added to the You have been added to the You have been added to the
45 <span style = <span style = <span style = <span style = "color: blue""color: blue""color: blue""color: blue">>>>
46 <strong> <strong> <strong> <strong>
47 <?php <?php <?php <?php printprintprintprint( ( ( ( "$book ""$book ""$book ""$book " ); ); ); ); ?>?>?>?>
48 </strong> </strong> </strong> </strong>
49 </span> </span> </span> </span>
50 mailing list. mailing list. mailing list. mailing list.
51 </ </ </ </p>p>p>p>
52 <strong> <strong> <strong> <strong>The following information has been saved The following information has been saved The following information has been saved The following information has been saved
53 in our database:in our database:in our database:in our database:</strong><br /></strong><br /></strong><br /></strong><br />
54
55 <table border = <table border = <table border = <table border = "0""0""0""0" cellpadding = cellpadding = cellpadding = cellpadding = "0""0""0""0" cellspacing = cellspacing = cellspacing = cellspacing = "10""10""10""10">>>>
56 <tr> <tr> <tr> <tr>
57 <td bgcolor = <td bgcolor = <td bgcolor = <td bgcolor = "#ffffaa""#ffffaa""#ffffaa""#ffffaa">>>>NNNName ame ame ame </td></td></td></td>
58 <td bgcolor =<td bgcolor =<td bgcolor =<td bgcolor = "#ffffbb""#ffffbb""#ffffbb""#ffffbb">>>>EmailEmailEmailEmail</td></td></td></td>
59 <td bgcolor = <td bgcolor = <td bgcolor = <td bgcolor = "#ffffcc""#ffffcc""#ffffcc""#ffffcc">>>>PhonePhonePhonePhone</td></td></td></td>
60 <td bgcolor = <td bgcolor = <td bgcolor = <td bgcolor = "#ffffdd""#ffffdd""#ffffdd""#ffffdd">>>>OSOSOSOS</td></td></td></td>
61 </tr> </tr> </tr> </tr>
62
63 <tr> <tr> <tr> <tr>
64 <?php<?php<?php<?php
65
form.php
(3 of 4)
2003 Prentice Hall, Inc.
All rights reserved.
Outline50
form.php
(4 of 4)
66 // print each form field’s value// print each form field’s value// print each form field’s value// print each form field’s value
67 printprintprintprint( ( ( ( "<td>$fname $lname</td>"<td>$fname $lname</td>"<td>$fname $lname</td>"<td>$fname $lname</td>
68 <td><td><td><td>$email$email$email$email</td></td></td></td>
69 <td>$phone</td><td>$phone</td><td>$phone</td><td>$phone</td>
70 <td>$os</td>"<td>$os</td>"<td>$os</td>"<td>$os</td>" ); ); ); );
71 ?>?>?>?>
72 </tr> </tr> </tr> </tr>
73 </table> </table> </table> </table>
74
75 <br /><br /><br /> <br /><br /><br /> <br /><br /><br /> <br /><br /><br />
76 <div style = <div style = <div style = <div style = "font"font"font"font----size: 10pt; textsize: 10pt; textsize: 10pt; textsize: 10pt; text----align: center"align: center"align: center"align: center">>>>
77 This is only a sample form. This is only a sample form. This is only a sample form. This is only a sample form.
78 You have not been added to a mailing list.You have not been added to a mailing list.You have not been added to a mailing list.You have not been added to a mailing list.
79 </di </di </di </div>v>v>v>
80 </body> </body> </body> </body>
81 </html></html></html></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.
Outline541 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.15: password.html Fig. 26.15: password.html Fig. 26.15: password.html Fig. 26.15: password.html -------->>>>
5 <!<!<!<!-------- XHTML form sent to password.php for ve XHTML form sent to password.php for ve XHTML form sent to password.php for ve XHTML form sent to password.php for verification rification rification rification -------->>>>
6
7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>
8 <head> <head> <head> <head>
9 <title> <title> <title> <title>Verifying a username and a password.Verifying a username and a password.Verifying a username and a password.Verifying a username and a password.</title></title></title></title>
10
11 <style<style<style<style typetypetypetype = = = = "text/css""text/css""text/css""text/css">>>>
12 td td td td {{{{ background background background background----color: color: color: color: #DDDDDD #DDDDDD #DDDDDD #DDDDDD }}}}
13 </style></style></style></style>
14 </head> </head> </head> </head>
15
16 <body style = <body style = <body style = <body style = "font"font"font"font----family: arial"family: arial"family: arial"family: arial">>>>
17 <p style = <p style = <p style = <p style = "font"font"font"font----size: 13pt"size: 13pt"size: 13pt"size: 13pt">>>>
18 Type in your username and password below. Type in your username and password below. Type in your username and password below. Type in your username and password below.
19 <br /> <br /> <br /> <br />
20 <span style = <span style = <span style = <span style = "color: #0000FF; font"color: #0000FF; font"color: #0000FF; font"color: #0000FF; font----sizsizsizsize: 10pt;e: 10pt;e: 10pt;e: 10pt;
21 font font font font----weight: bold"weight: bold"weight: bold"weight: bold">>>>
22 Note that password will be sent as plain textNote that password will be sent as plain textNote that password will be sent as plain textNote that password will be sent as plain text
23 </span> </span> </span> </span>
24 </p> </p> </p> </p>
25
password.html
(1 of 4)
2003 Prentice Hall, Inc.
All rights reserved.
Outline55
26 <!<!<!<!-------- post form data to password.php post form data to password.php post form data to password.php post form data to password.php -------->>>>
27 <form action = <form action = <form action = <form action = "password.php""password.php""password.php""password.php" method = method = method = method = "post""post""post""post">>>>
28 <br /> <br /> <br /> <br />
29
30 <table border = <table border = <table border = <table border = "0""0""0""0" cellspacing = cellspacing = cellspacing = cellspacing = "0""0""0""0"
31 style = style = style = style = "height: 90px; width: 123px; "height: 90px; width: 123px; "height: 90px; width: 123px; "height: 90px; width: 123px;
32 fontfontfontfont----size: 10pt" size: 10pt" size: 10pt" size: 10pt" cellpadding = cellpadding = cellpadding = cellpadding = "0""0""0""0">>>>
33
34 <tr> <tr> <tr> <tr>
35 <td colspan = <td colspan = <td colspan = <td colspan = "3""3""3""3"> > > >
36 <strong> <strong> <strong> <strong>Username:Username:Username:Username:</strong></strong></strong></strong>
37 </td> </td> </td> </td>
38 </tr> </tr> </tr> </tr>
39
40 <tr> <tr> <tr> <tr>
41 <td colspan = <td colspan = <td colspan = <td colspan = "3""3""3""3">>>>
42 <input size = <input size = <input size = <input size = "40""40""40""40" name = name = name = name = "USERNAME""USERNAME""USERNAME""USERNAME"
43 style = style = style = style = "height: 22px; width: 115px""height: 22px; width: 115px""height: 22px; width: 115px""height: 22px; width: 115px" /> /> /> />
44 </td> </td> </td> </td>
45 </tr> </tr> </tr> </tr>
46
password.html
(2 of 4)
Form data is posted to password.php.
2003 Prentice Hall, Inc.
All rights reserved.
Outline56
47 <tr> <tr> <tr> <tr>
48 <td colspan = <td colspan = <td colspan = <td colspan = "3""3""3""3">>>>
49 <strong> <strong> <strong> <strong>Password:Password:Password:Password:</strong></strong></strong></strong>
50 </td> </td> </td> </td>
51 </tr> </tr> </tr> </tr>
52
53 <tr> <tr> <tr> <tr>
54 <td colspan = <td colspan = <td colspan = <td colspan = "3""3""3""3">>>>
55 <input size = <input size = <input size = <input size = "40""40""40""40" name = name = name = name = "PASSWORD""PASSWORD""PASSWORD""PASSWORD"
56 style = style = style = style = "height: 22px; width: 115px""height: 22px; width: 115px""height: 22px; width: 115px""height: 22px; width: 115px"
57 type = type = type = type = "password""password""password""password" /> /> /> />
58 <br/></td> <br/></td> <br/></td> <br/></td>
59 </tr> </tr> </tr> </tr>
60
61 <tr> <tr> <tr> <tr>
62 <td colspan = <td colspan = <td colspan = <td colspan = "1""1""1""1">>>>
63 <input type =<input type =<input type =<input type = "submit""submit""submit""submit" name = name = name = name = "Enter""Enter""Enter""Enter"
64 value = value = value = value = "Enter" "Enter" "Enter" "Enter" style =style =style =style = "height: 23px;"height: 23px;"height: 23px;"height: 23px;
65 width: 47px" width: 47px" width: 47px" width: 47px" />/>/>/>
66 </td> </td> </td> </td>
67 <td colspan = <td colspan = <td colspan = <td colspan = "2""2""2""2">>>>
68 <input type =<input type =<input type =<input type = "submit""submit""submit""submit" name =name =name =name = "NewUser""NewUser""NewUser""NewUser"
69 value = value = value = value = "New User""New User""New User""New User"
70 style = style = style = style = "height: 23px""height: 23px""height: 23px""height: 23px" />/>/>/>
71 </td> </td> </td> </td>
password.html
(3 of 4)
2003 Prentice Hall, Inc.
All rights reserved.
Outline57
72 </tr> </tr> </tr> </tr>
73 </table> </table> </table> </table>
74 </form> </form> </form> </form>
75 </body> </body> </body> </body>
76 </html></html></html></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.
Outline591 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.16: password.php Fig. 26.16: password.php Fig. 26.16: password.php Fig. 26.16: password.php -------->>>>
5 <!<!<!<!-------- Searching a database for usernames an Searching a database for usernames an Searching a database for usernames an Searching a database for usernames and passwords. d passwords. d passwords. d passwords. -------->>>>
6
7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>
8 <head> <head> <head> <head>
9 <?php<?php<?php<?php
10 extract( $_POST ); extract( $_POST ); extract( $_POST ); extract( $_POST );
11
12 // check if user has left USERNAME or PASSWORD field blank// check if user has left USERNAME or PASSWORD field blank// check if user has left USERNAME or PASSWORD field blank// check if user has left USERNAME or PASSWORD field blank
13 ifififif ( ( ( ( !$USERNAME !$USERNAME !$USERNAME !$USERNAME || !$PASSWORD|| !$PASSWORD|| !$PASSWORD|| !$PASSWORD ) { ) { ) { ) {
14 fieldsBlank(); fieldsBlank(); fieldsBlank(); fieldsBlank();
15 die(); die(); die(); die();
16 } } } }
17
18 // check if the New User button was clicked // check if the New User button was clicked // check if the New User button was clicked // check if the New User button was clicked
19 if if if if ( ( ( ( isset( $NewUser )isset( $NewUser )isset( $NewUser )isset( $NewUser ) ) { ) { ) { ) {
20
21 // open password.txt for writi// open password.txt for writi// open password.txt for writi// open password.txt for writing using append modeng using append modeng using append modeng using append mode
22 ifififif ( !( $file = fopen( ( !( $file = fopen( ( !( $file = fopen( ( !( $file = fopen( "password.txt""password.txt""password.txt""password.txt",,,,
23 "a""a""a""a" ) ) ) { ) ) ) { ) ) ) { ) ) ) {
24
password.php
(1 of 7)
Variable names, when preceded by the logical
negation operator (!), return true if they are empty
or set to 0. This checks if a user has submitted a form
without specifying a username or password.
Function fieldsBlank is called if the user has
submitted an incomplete form to notify the user
that all form fields must be completed.Function isset tests whether the user has
pressed the New User button, indicating that a
new user must be added.
To add a new user, we open the file
password.txt in append mode and assign the
file handle that is returned to variable $file.
2003 Prentice Hall, Inc.
All rights reserved.
Outline60
25 // print error message and terminate script // print error message and terminate script // print error message and terminate script // print error message and terminate script
26 // execution if file cannot be opened // execution if file cannot be opened // execution if file cannot be opened // execution if file cannot be opened
27 printprintprintprint( ( ( ( "<title>Error</title></head><body>"<title>Error</title></head><body>"<title>Error</title></head><body>"<title>Error</title></head><body>
28 Could not open password fileCould not open password fileCould not open password fileCould not open password file
29 </body></html>"</body></html>"</body></html>"</body></html>" ); ); ); );
30 die();die();die();die();
31 } } } }
32
33 // write username and password to file and // write username and password to file and // write username and password to file and // write username and password to file and
34 // call function userAdded // call function userAdded // call function userAdded // call function userAdded
35 fputs( $file, fputs( $file, fputs( $file, fputs( $file, "$USERNAME,$PASSWORD"$USERNAME,$PASSWORD"$USERNAME,$PASSWORD"$USERNAME,$PASSWORD\\\\n"n"n"n" ); ); ); );
36 userAdded( $USERNAME ); userAdded( $USERNAME ); userAdded( $USERNAME ); userAdded( $USERNAME );
37 }}}}
38 elseelseelseelse { { { {
39
40 // if a new user is not being added, open file // if a new user is not being added, open file // if a new user is not being added, open file // if a new user is not being added, open file
41 // for reading // for reading // for reading // for reading
42 ifififif ( !( $file = fopen( ( !( $file = fopen( ( !( $file = fopen( ( !( $file = fopen( "password.txt""password.txt""password.txt""password.txt",,,,
43 "r""r""r""r" ) ) ) { ) ) ) { ) ) ) { ) ) ) {
44 printprintprintprint( ( ( ( "<title>Error</title></head>"<title>Error</title></head>"<title>Error</title></head>"<title>Error</title></head>
45 <body>Could not open password file<body>Could not open password file<body>Could not open password file<body>Could not open password file
46 </body></html>"</body></html>"</body></html>"</body></html>" ); ); ); );
47 die(); die(); die(); die();
48 } } } }
49
password.php
(2 of 7)Print an error message and terminate script execution
if the file cannot be opened.
Function fputs writes the name and password to the
text file..
Function userAdded is called to print a message to the
user to indicate that the username and password were
added to the file.
2003 Prentice Hall, Inc.
All rights reserved.
Outline61
50 $userVerified = $userVerified = $userVerified = $userVerified = 0000;;;;
51
52 // read each line in file and check username // read each line in file and check username // read each line in file and check username // read each line in file and check username
53 // and password // and password // and password // and password
54 while while while while ( ( ( ( !feof( $file )!feof( $file )!feof( $file )!feof( $file ) && !$userVerified ) { && !$userVerified ) { && !$userVerified ) { && !$userVerified ) {
55
56 // read line from file// read line from file// read line from file// read line from file
57 $line = $line = $line = $line = fgets( $file, fgets( $file, fgets( $file, fgets( $file, 255255255255 ) ) ) );;;;
58
59 // remove newline character from end of line // remove newline character from end of line // remove newline character from end of line // remove newline character from end of line
60 $line = $line = $line = $line = chop( $line )chop( $line )chop( $line )chop( $line );;;;
61
62 // split username and password// split username and password// split username and password// split username and password
63 $field$field$field$field = = = = split( split( split( split( ","","","",", $line, , $line, , $line, , $line, 2222 ) ) ) );;;;
64
65 // verify username// verify username// verify username// verify username
66 if if if if ( $USERNAME == $field[ ( $USERNAME == $field[ ( $USERNAME == $field[ ( $USERNAME == $field[ 0000 ] ) { ] ) { ] ) { ] ) {
67 $userVerified = $userVerified = $userVerified = $userVerified = 1111;;;;
68
69 // call function checkPassword to verify // call function checkPassword to verify // call function checkPassword to verify // call function checkPassword to verify
70 // user’s password // user’s password // user’s password // user’s password
71 if if if if ( checkPassword( $PASSWORD, $field ) ( checkPassword( $PASSWORD, $field ) ( checkPassword( $PASSWORD, $field ) ( checkPassword( $PASSWORD, $field )
72 == == == == truetruetruetrue ) ) ) )
73 accessGranted( $USERNAME );accessGranted( $USERNAME );accessGranted( $USERNAME );accessGranted( $USERNAME );
74 else else else else
75 wrowrowrowrongPassword();ngPassword();ngPassword();ngPassword();
password.php
(3 of 7)
Before entering the while loop, variable
$userVerified is set to 0.
The while loop executes as long as the there are more
lines in the file to read and variable $userVerified is
still 0 or empty.
Function fgets reads a line from the text file.
The result is assigned to variable $line.
Function chop removes the newline character
from the end of the line.Function split is called to separate the string at the
specified delimiter (in this case, a comma). The
resulting array is stored in array $field.The username entered by the user is tested
against the one returned in the text file (stored
in the first element of the array). If they match,
variable $userVerified is set to 1.
Function checkPassword is called to verify
the user’s password. Variable $PASSWORD and
array $field are passed to the function.
If function checkPassword returns true, function
accessGranted is called to notify the client that
permission has been granted. Otherwise, function
wrongPassword is called.
2003 Prentice Hall, Inc.
All rights reserved.
Outline62
76 }}}}
77 }}}}
78
79 // close text file // close text file // close text file // close text file
80 fclose( $file );fclose( $file );fclose( $file );fclose( $file );
81
82 // call function accessDenied if username has // call function accessDenied if username has // call function accessDenied if username has // call function accessDenied if username has
83 // not been verified // not been verified // not been verified // not been verified
84 ifififif ( !$userVerified ) ( !$userVerified ) ( !$userVerified ) ( !$userVerified )
85 accessDenied();accessDenied();accessDenied();accessDenied();
86 } } } }
87
88 // // // // verify user password and return a booleanverify user password and return a booleanverify user password and return a booleanverify user password and return a boolean
89 functionfunctionfunctionfunction checkPassword( $userpassword, $filedata ) checkPassword( $userpassword, $filedata ) checkPassword( $userpassword, $filedata ) checkPassword( $userpassword, $filedata )
90 { { { {
91 ifififif ( $userp ( $userp ( $userp ( $userpassword == $filedata[ assword == $filedata[ assword == $filedata[ assword == $filedata[ 1111 ] ) ] ) ] ) ] )
92 returnreturnreturnreturn truetruetruetrue;;;;
93 elseelseelseelse
94 returnreturnreturnreturn falsefalsefalsefalse;;;;
95 } } } }
96
password.php
(4 of 7)
After the while loop has executed, function
fclose is called to close the file.
If variable $userVerified has not been set to a
value other than 0, function accessDenied is
called to notify the client that access has been
denied.
Function checkPassword compares the user’s
password to the password in the file. If they match,
true is returned, whereas false is returned if they
do not.
2003 Prentice Hall, Inc.
All rights reserved.
Outline63
97 // print a message indicating the user has been added // print a message indicating the user has been added // print a message indicating the user has been added // print a message indicating the user has been added
98 function function function function userAdded( $name ) userAdded( $name ) userAdded( $name ) userAdded( $name )
99 {{{{
100 printprintprintprint( ( ( ( "<title>Thank You</title></head>"<title>Thank You</title></head>"<title>Thank You</title></head>"<title>Thank You</title></head>
101 <body style = <body style = <body style = <body style = \\\\"font"font"font"font----family: arial; family: arial; family: arial; family: arial;
102 font font font font----size: 1em; color: bluesize: 1em; color: bluesize: 1em; color: bluesize: 1em; color: blue\\\\"> "> "> ">
103 <strong>You have been added <strong>You have been added <strong>You have been added <strong>You have been added
104 to the user list, $name. to the user list, $name. to the user list, $name. to the user list, $name.
105 <br />Enjoy the site.</strong>"<br />Enjoy the site.</strong>"<br />Enjoy the site.</strong>"<br />Enjoy the site.</strong>" ); ); ); );
106 }}}}
107
108 // print a message in // print a message in // print a message in // print a message indicating permission dicating permission dicating permission dicating permission
109 // has been granted // has been granted // has been granted // has been granted
110 function function function function accessGranted( $name ) accessGranted( $name ) accessGranted( $name ) accessGranted( $name )
111 { { { {
112 printprintprintprint( ( ( ( "<title>Thank You</title></head>"<title>Thank You</title></head>"<title>Thank You</title></head>"<title>Thank You</title></head>
113 <body style = <body style = <body style = <body style = \\\\"font"font"font"font----family: arial;family: arial;family: arial;family: arial;
114 font font font font----size: 1em; color: bluesize: 1em; color: bluesize: 1em; color: bluesize: 1em; color: blue\\\\">">">">
115 <strong>Permission has been <strong>Permission has been <strong>Permission has been <strong>Permission has been
116 granted, $name. <br /> granted, $name. <br /> granted, $name. <br /> granted, $name. <br />
117 Enjoy the site.</strong>"Enjoy the site.</strong>"Enjoy the site.</strong>"Enjoy the site.</strong>" ); ); ); );
118 } } } }
119
password.php
(5 of 7)Function userAdded prints a message to the
client indicating that the user has been added.
Function accessGranted prints a
message to the client indicating that
permission has been granted.
2003 Prentice Hall, Inc.
All rights reserved.
Outline64
120 // print a message indicating password is invalid // print a message indicating password is invalid // print a message indicating password is invalid // print a message indicating password is invalid
121 function function function function wrongPassword() wrongPassword() wrongPassword() wrongPassword()
122 { { { {
123 printprintprintprint( ( ( ( "<title>Access Denied</title></head>"<title>Access Denied</title></head>"<title>Access Denied</title></head>"<title>Access Denied</title></head>
124 <body style = <body style = <body style = <body style = \\\\"font"font"font"font----family: arial; family: arial; family: arial; family: arial;
125 font font font font----size: 1em; color: redsize: 1em; color: redsize: 1em; color: redsize: 1em; color: red\\\\">">">">
126 <strong>You entered an invalid <strong>You entered an invalid <strong>You entered an invalid <strong>You entered an invalid
127 password.<br />Access has password.<br />Access has password.<br />Access has password.<br />Access has
128 been denied.</strong>"been denied.</strong>"been denied.</strong>"been denied.</strong>" ); ); ); );
129 }}}}
130
131 // print a message indicating a // print a message indicating a // print a message indicating a // print a message indicating access has been deniedccess has been deniedccess has been deniedccess has been denied
132 function function function function accessDenied() accessDenied() accessDenied() accessDenied()
133 { { { {
134 printprintprintprint( ( ( ( "<title>Access Denied</title></head>"<title>Access Denied</title></head>"<title>Access Denied</title></head>"<title>Access Denied</title></head>
135 <body style = <body style = <body style = <body style = \\\\"font"font"font"font----family: arial; family: arial; family: arial; family: arial;
136 font font font font----size: 1em; color: redsize: 1em; color: redsize: 1em; color: redsize: 1em; color: red\\\\">">">">
137 <strong> <strong> <strong> <strong>
138 You were denied access to this server. You were denied access to this server. You were denied access to this server. You were denied access to this server.
139 <br /></strong>" <br /></strong>" <br /></strong>" <br /></strong>" ););););
140 } } } }
141
password.php
(6 of 7)
Function wrongPassword prints a message to the
client indicating that the password is invalid.
Function accessDenied prints a message to the
client indicating that access has been denied.
2003 Prentice Hall, Inc.
All rights reserved.
Outline65
142 // print a message indicating that fields // print a message indicating that fields // print a message indicating that fields // print a message indicating that fields
143 // have been left blank // have been left blank // have been left blank // have been left blank
144 function function function function fieldsBlank() fieldsBlank() fieldsBlank() fieldsBlank()
145 { { { {
146 printprintprintprint( ( ( ( "<title>Access Denied</title></head>"<title>Access Denied</title></head>"<title>Access Denied</title></head>"<title>Access Denied</title></head>
147 <body style = <body style = <body style = <body style = \\\\"font"font"font"font----family: arial; family: arial; family: arial; family: arial;
148 font font font font----size: 1em; color: redsize: 1em; color: redsize: 1em; color: redsize: 1em; color: red\\\\">">">">
149 <strong> <strong> <strong> <strong>
150 Please fill in all form fields. Please fill in all form fields. Please fill in all form fields. Please fill in all form fields.
151 <br /></strong>" <br /></strong>" <br /></strong>" <br /></strong>" ););););
152 } } } }
153 ?>?>?>?>
154 </body> </body> </body> </body>
155 </html></html></html></html>
password.php
(7 of 7)
Function fieldsBlank prints a message to the
client indicating that all form fields have not been
completed.
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.
Outline67
password.txt
(1 of 1)
1 account1,password1account1,password1account1,password1account1,password1
2 account2,password2account2,password2account2,password2account2,password2
3 account3,password3account3,password3account3,password3account3,password3
4 account4,password4account4,password4account4,password4account4,password4
5 account5,password5account5,password5account5,password5account5,password5
6 account6,password6account6,password6account6,password6account6,password6
7 account7,password7account7,password7account7,password7account7,password7
8 account8,password8account8,password8account8,password8account8,password8
9 account9,password9account9,password9account9,password9account9,password9
10 account10,password10account10,password10account10,password10account10,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.
Outline691 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.18: data.html Fig. 26.18: data.html Fig. 26.18: data.html Fig. 26.18: data.html -------->>>>
5 <!<!<!<!-------- Querying a MySQL Database Querying a MySQL Database Querying a MySQL Database Querying a MySQL Database -------->>>>
6
7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "htt"htt"htt"http://www.w3.org/1999/xhtml"p://www.w3.org/1999/xhtml"p://www.w3.org/1999/xhtml"p://www.w3.org/1999/xhtml">>>>
8 <head> <head> <head> <head>
9 <title> <title> <title> <title>Sample Database QuerySample Database QuerySample Database QuerySample Database Query</title></title></title></title>
10 </head> </head> </head> </head>
11
12 <body style = <body style = <body style = <body style = "background"background"background"background----color: #F0E68C"color: #F0E68C"color: #F0E68C"color: #F0E68C">>>>
13 <h2 style = <h2 style = <h2 style = <h2 style = "font"font"font"font----family: arial color: blue"family: arial color: blue"family: arial color: blue"family: arial color: blue">>>>
14 Querying a MySQuerying a MySQuerying a MySQuerying a MySQL database.QL database.QL database.QL database.
15 </h2> </h2> </h2> </h2>
16
17 <form method = <form method = <form method = <form method = "post""post""post""post" action = action = action = action = "database.php""database.php""database.php""database.php">>>>
18 <p> <p> <p> <p>Select a field to display:Select a field to display:Select a field to display:Select a field to display:
19
20 <! <! <! <!-------- add a select box containing options add a select box containing options add a select box containing options add a select box containing options --------> > > >
21 <! <! <! <!-------- for SELECT query for SELECT query for SELECT query for SELECT query -------->>>>
data.html
(1 of 2)
2003 Prentice Hall, Inc.
All rights reserved.
Outline70
22 <select name = <select name = <select name = <select name = "select""select""select""select">>>>
23 <option selected = <option selected = <option selected = <option selected = "selected""selected""selected""selected">>>>****</option></option></option></option>
24 <option><option><option><option>IDIDIDID</option></option></option></option>
25 <option><option><option><option>TitleTitleTitleTitle</option></option></option></option>
26 <option><option><option><option>CategoryCategoryCategoryCategory</option></option></option></option>
27 <option><option><option><option>ISBNISBNISBNISBN</option></option></option></option>
28 </select></select></select></select>
29 </p> </p> </p> </p>
30
31 <input type = <input type = <input type = <input type = "submit""submit""submit""submit" value = value = value = value = "Send "Send "Send "Send Query"Query"Query"Query"
32 style = style = style = style = "background"background"background"background----color: blue; color: blue; color: blue; color: blue;
33 color: yellow; fontcolor: yellow; fontcolor: yellow; fontcolor: yellow; font----weight: bold"weight: bold"weight: bold"weight: bold" />/>/>/>
34 </form> </form> </form> </form>
35 </body> </body> </body> </body>
36 </html></html></html></html>
data.html
(2 of 2)
Select box containing options for a SELECT
query.
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.
Outline731 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.19: database.php Fig. 26.19: database.php Fig. 26.19: database.php Fig. 26.19: database.php -------->>>>
5 <!<!<!<!-------- Program to query a database and Program to query a database and Program to query a database and Program to query a database and -------->>>>
6 <!<!<!<!-------- send res send res send res send results to the client. ults to the client. ults to the client. ults to the client. -------->>>>
7
8 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>
9 <head> <head> <head> <head>
10 <title> <title> <title> <title>Search ResultsSearch ResultsSearch ResultsSearch Results</title></title></title></title>
11 </head> </head> </head> </head>
12
13 <body style = <body style = <body style = <body style = "font"font"font"font----family: arial, sansfamily: arial, sansfamily: arial, sansfamily: arial, sans----serif"serif"serif"serif"
14 style = style = style = style = "backgroun"backgroun"backgroun"backgroundddd----color: #F0E68C"color: #F0E68C"color: #F0E68C"color: #F0E68C">>>>
15 <?php<?php<?php<?php
16
17 extract( $_POST ); extract( $_POST ); extract( $_POST ); extract( $_POST );
18
19 // build SELECT query // build SELECT query // build SELECT query // build SELECT query
20 $query = $query = $query = $query = "SELECT ""SELECT ""SELECT ""SELECT " . $select . . $select . . $select . . $select . " FROM Books"" FROM Books"" FROM Books"" FROM Books";;;;
21
22 // Connect to MySQL // Connect to MySQL // Connect to MySQL // Connect to MySQL
23 ifififif ( !( $databas ( !( $databas ( !( $databas ( !( $database = e = e = e = mysql_connectmysql_connectmysql_connectmysql_connect( ( ( ( "localhost""localhost""localhost""localhost",,,,
24 "httpd""httpd""httpd""httpd", , , , """""""" ) ) ) ) ) ) ) ) ) ) ) )
25 diediediedie( ( ( ( "Could not connect to database""Could not connect to database""Could not connect to database""Could not connect to database" ); ); ); );
database.php
(1 of 3)
Build the select query and assign the
string to variable $query.
Function mysql_connect returns a database
handle which represents PHP’s connection to a
database. If this connection is not made, function
die is called to terminate script execution.
2003 Prentice Hall, Inc.
All rights reserved.
Outline74
26
27 // open Products database // open Products database // open Products database // open Products database
28 if if if if ( ( ( ( !!!!mysql_select_dbmysql_select_dbmysql_select_dbmysql_select_db( ( ( ( "Products""Products""Products""Products", $database ), $database ), $database ), $database ) ) ) ) )
29 diediediedie( ( ( ( "Could not open Products database""Could not open Products database""Could not open Products database""Could not open Products database" ); ); ); );
30
31 // query Products database // query Products database // query Products database // query Products database
32 ifififif ( ( ( ( !( $resul!( $resul!( $resul!( $result = t = t = t = mysql_querymysql_querymysql_querymysql_query( $query, $database ) )( $query, $database ) )( $query, $database ) )( $query, $database ) ) ) { ) { ) { ) {
33 print print print print( ( ( ( "Could not execute query! <br />""Could not execute query! <br />""Could not execute query! <br />""Could not execute query! <br />" ); ); ); );
34 diediediedie( ( ( ( mysql_errormysql_errormysql_errormysql_error() );() );() );() );
35 } } } }
36 ?>?>?>?>
37
38 <h3 style = <h3 style = <h3 style = <h3 style = "color: blue""color: blue""color: blue""color: blue">>>>
39 Search ResultsSearch ResultsSearch ResultsSearch Results</h3></h3></h3></h3>
40
41 <table border = <table border = <table border = <table border = "1""1""1""1" cellpadding = cellpadding = cellpadding = cellpadding = "3""3""3""3" cellspacing = cellspacing = cellspacing = cellspacing = "2""2""2""2"
42 style =style =style =style = "background"background"background"background----color: #ADD8E6"color: #ADD8E6"color: #ADD8E6"color: #ADD8E6">>>>
43
44 <?php<?php<?php<?php
45
46 // fetch each record in result set// fetch each record in result set// fetch each record in result set// fetch each record in result set
47 for for for for ( $counter = ( $counter = ( $counter = ( $counter = 0000; ; ; ;
48 $row = $row = $row = $row = mysql_fetch_rowmysql_fetch_rowmysql_fetch_rowmysql_fetch_row( $result );( $result );( $result );( $result );
49 $counter++ ){ $counter++ ){ $counter++ ){ $counter++ ){
50
database.php
(2 of 3)
Function mysql_select_db is called to specify the
database to be queried.
Function mysql_query returns an object
containing the result set of the query, which
we assign to variable $result.
The for loop iterates through each
record in the result set while
constructing an XHTML table from
the results. Variable $counter is
incremented by one for each row
retrieved. Function mysql_fetch_row returns an
array containing the elements of each
row in the result set of our query
($result).
2003 Prentice Hall, Inc.
All rights reserved.
Outline75
51 // build table to display results// build table to display results// build table to display results// build table to display results
52 printprintprintprint( ( ( ( "<tr>""<tr>""<tr>""<tr>" ); ); ); );
53
54 foreach foreach foreach foreach ( $row ( $row ( $row ( $row asasasas $key => $value ) $key => $value ) $key => $value ) $key => $value )
55 print print print print( ( ( ( "<td>$value</td>""<td>$value</td>""<td>$value</td>""<td>$value</td>" ); ); ); );
56
57 print print print print( ( ( ( "</tr>""</tr>""</tr>""</tr>" ); ); ); );
58 } } } }
59
60 mysql_closemysql_closemysql_closemysql_close( $database );( $database );( $database );( $database );
61 ?>?>?>?>
62
63 </table> </table> </table> </table>
64
65 <br /> <br /> <br /> <br />Your search yielded Your search yielded Your search yielded Your search yielded <strong><strong><strong><strong>
66 <?php<?php<?php<?php print print print print( ( ( ( "$counter""$counter""$counter""$counter" ) ) ) ) ?> ?> ?> ?> results.results.results.results.<br /><br /></strong><br /><br /></strong><br /><br /></strong><br /><br /></strong>
67
68 <h5> <h5> <h5> <h5>Please email comments toPlease email comments toPlease email comments toPlease email comments to
69 <a href = <a href = <a href = <a href = "mailto:[email protected]""mailto:[email protected]""mailto:[email protected]""mailto:[email protected]">>>>
70 Deitel and Associates, Inc.Deitel and Associates, Inc.Deitel and Associates, Inc.Deitel and Associates, Inc.
71 </a> </a> </a> </a>
72 </h5> </h5> </h5> </h5>
73
74 </body> </body> </body> </body>
75 </html></html></html></html>
database.php
(3 of 3)
The foreach loop iterates through the
array containing the elements of each row
and prints out each element in an
individual table cell.The total number of results are printed to the
client.
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.
Outline781 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.20: cookies.html Fig. 26.20: cookies.html Fig. 26.20: cookies.html Fig. 26.20: cookies.html -------->>>>
5 <!<!<!<!-------- Writing a Cookie Writing a Cookie Writing a Cookie Writing a Cookie -------->>>>
6
7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http:"http:"http:"http://www.w3.org/1999/xhtml"//www.w3.org/1999/xhtml"//www.w3.org/1999/xhtml"//www.w3.org/1999/xhtml">>>>
8 <head> <head> <head> <head>
9 <title><title><title><title>Writing a cookie to the client computerWriting a cookie to the client computerWriting a cookie to the client computerWriting a cookie to the client computer</title></title></title></title>
10 </head> </head> </head> </head>
11
12 <body style = <body style = <body style = <body style = "font"font"font"font----family: arial, sansfamily: arial, sansfamily: arial, sansfamily: arial, sans----serif; serif; serif; serif;
13 backgroundbackgroundbackgroundbackground----color: #99CCFF"color: #99CCFF"color: #99CCFF"color: #99CCFF">>>>
14
15 <h2> <h2> <h2> <h2>Click Write Cookie to save your cookie data.Click Write Cookie to save your cookie data.Click Write Cookie to save your cookie data.Click Write Cookie to save your cookie data.</h2></h2></h2></h2>
16
cookies.html
(1 of 2)
2003 Prentice Hall, Inc.
All rights reserved.
Outline79
17 <form method = <form method = <form method = <form method = "post""post""post""post" action = action = action = action = "cookies.php""cookies.php""cookies.php""cookies.php"
18 style =style =style =style = "font"font"font"font----size: 10pt"size: 10pt"size: 10pt"size: 10pt">>>>
19 <strong><strong><strong><strong>Name:Name:Name:Name:</strong><br /></strong><br /></strong><br /></strong><br />
20 <input type = <input type = <input type = <input type = "text""text""text""text" name = name = name = name = "NAME""NAME""NAME""NAME" /> /> /> /><br /><br /><br /><br />
21
22 <strong> <strong> <strong> <strong>Height:Height:Height:Height:</s</s</s</strong><br />trong><br />trong><br />trong><br />
23 <input type = <input type = <input type = <input type = "text""text""text""text" name = name = name = name = "HEIGHT""HEIGHT""HEIGHT""HEIGHT" /> /> /> /><br /><br /><br /><br />
24
25 <strong> <strong> <strong> <strong>Favorite Color:Favorite Color:Favorite Color:Favorite Color:</strong><br /></strong><br /></strong><br /></strong><br />
26 <input type = <input type = <input type = <input type = "text""text""text""text" name = name = name = name = "COLOR""COLOR""COLOR""COLOR" /> /> /> /><br /><br /><br /><br />
27
28 <input type = <input type = <input type = <input type = "submit""submit""submit""submit" value = value = value = value = "Write C"Write C"Write C"Write Cookie" ookie" ookie" ookie"
29 stylestylestylestyle = = = = "background"background"background"background----color: #F0E86C; color: navy;color: #F0E86C; color: navy;color: #F0E86C; color: navy;color: #F0E86C; color: navy;
30 fontfontfontfont----weight: bold"weight: bold"weight: bold"weight: bold" /></p> /></p> /></p> /></p>
31 </form> </form> </form> </form>
32 </body> </body> </body> </body>
33 </html></html></html></html>
cookies.html
(2 of 2)
Form data is posted to cookies.php.
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.
Outline811 <?php <?php <?php <?php
2 // Fig. 26.21: cookies.php// Fig. 26.21: cookies.php// Fig. 26.21: cookies.php// Fig. 26.21: cookies.php
3 // Program to write a cookie to a client's machine// Program to write a cookie to a client's machine// Program to write a cookie to a client's machine// Program to write a cookie to a client's machine
4
5 extract( $_POST ); extract( $_POST ); extract( $_POST ); extract( $_POST );
6 // write each form field’s value to a cookie and set the // write each form field’s value to a cookie and set the // write each form field’s value to a cookie and set the // write each form field’s value to a cookie and set the
7 // cookie’s expiration date // cookie’s expiration date // cookie’s expiration date // cookie’s expiration date
8 setcookiesetcookiesetcookiesetcookie( ( ( ( "Name""Name""Name""Name", $NAME, time() + , $NAME, time() + , $NAME, time() + , $NAME, time() + 60606060 * * * * 60606060 * * * * 24242424 * * * * 5555 ); ); ); );
9 setcookiesetcookiesetcookiesetcookie( ( ( ( "Height""Height""Height""Height", $HEIGHT, time() + , $HEIGHT, time() + , $HEIGHT, time() + , $HEIGHT, time() + 60606060 * * * * 60606060 * * * * 24242424 * * * * 5555 ); ); ); );
10 setcookiesetcookiesetcookiesetcookie( ( ( ( "Color""Color""Color""Color", $COLOR, time() + , $COLOR, time() + , $COLOR, time() + , $COLOR, time() + 60606060 * * * * 60606060 * * * * 24242424 * * * * 5555 ); ); ); );
11 ?>?>?>?>
12
13 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1//W3C//DTD XHTML 1//W3C//DTD XHTML 1//W3C//DTD XHTML 1.0 Transitional//EN".0 Transitional//EN".0 Transitional//EN".0 Transitional//EN"
14 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
15
16 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>
17 <head> <head> <head> <head>
18 <title> <title> <title> <title>Cookie SavedCookie SavedCookie SavedCookie Saved</title></title></title></title>
19 </head> </head> </head> </head>
20
21 <body style = <body style = <body style = <body style = "font"font"font"font----family: arial, sansfamily: arial, sansfamily: arial, sansfamily: arial, sans----serif"serif"serif"serif">>>>
22 <p> <p> <p> <p>The cookie has been set with the following data:The cookie has been set with the following data:The cookie has been set with the following data:The cookie has been set with the following data:</p></p></p></p>
23
cookies.php
(1 of 2)
Function setcookie takes the name of the
cookie to be set as the first argument,
followed by the value to be stored in the
cookie. The optional third argument specifies
the expiration date of the cookie.
2003 Prentice Hall, Inc.
All rights reserved.
Outline82
24 <!<!<!<!-------- print each form field’s value print each form field’s value print each form field’s value print each form field’s value -------->>>>
25 <br /><span style = <br /><span style = <br /><span style = <br /><span style = "color: blue""color: blue""color: blue""color: blue">>>>Name:Name:Name:Name:</span> </span> </span> </span>
26 <?php<?php<?php<?php printprintprintprint( $NAME ) ( $NAME ) ( $NAME ) ( $NAME ) ?>?>?>?><br /><br /><br /><br />
27
28 <span style = <span style = <span style = <span style = "color: blue""color: blue""color: blue""color: blue">>>>Height:Height:Height:Height:</span> </span> </span> </span>
29 <?php<?php<?php<?php print print print print( ( ( ( $HEI$HEI$HEI$HEIGHT ) GHT ) GHT ) GHT ) ?>?>?>?><br /><br /><br /><br />
30
31 <span style = <span style = <span style = <span style = "color: blue""color: blue""color: blue""color: blue">>>>Favorite Color:Favorite Color:Favorite Color:Favorite Color:</span></span></span></span>
32
33 <span style = <span style = <span style = <span style = "color:"color:"color:"color: <?php<?php<?php<?php print print print print( ( ( ( "$COLOR"$COLOR"$COLOR"$COLOR\\\\">$COLOR"">$COLOR"">$COLOR"">$COLOR" ) ) ) ) ?>?>?>?>
34 </span><br /> </span><br /> </span><br /> </span><br />
35 <p> <p> <p> <p>Click Click Click Click <a href = <a href = <a href = <a href = "readCookies.php""readCookies.php""readCookies.php""readCookies.php">>>>herehereherehere</a</a</a</a>>>>
36 to read the saved cookie. to read the saved cookie. to read the saved cookie. to read the saved cookie.</p></p></p></p>
37 </body> </body> </body> </body>
38 </html></html></html></html>
cookies.php
(2 of 2)
Each form field’s value is printed to
confirm the data that has been set as a
cookie with the user.
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.
Outline871 <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC <!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.24: readCookies.php Fig. 26.24: readCookies.php Fig. 26.24: readCookies.php Fig. 26.24: readCookies.php -------->>>>
5 <!<!<!<!-------- Program to read cookies from the cli Program to read cookies from the cli Program to read cookies from the cli Program to read cookies from the client's computer ent's computer ent's computer ent's computer -------->>>>
6
7 <html xmlns = <html xmlns = <html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>
8 <head><title> <head><title> <head><title> <head><title>Read CookiesRead CookiesRead CookiesRead Cookies</title></head></title></head></title></head></title></head>
9
10 <body style = <body style = <body style = <body style = "font"font"font"font----family: arial, sansfamily: arial, sansfamily: arial, sansfamily: arial, sans----serif"serif"serif"serif">>>>
11
12 <p> <p> <p> <p>
13 <strong> <strong> <strong> <strong>
14 The following data is saved in a cookie on your The following data is saved in a cookie on your The following data is saved in a cookie on your The following data is saved in a cookie on your
15 computer.computer.computer.computer.
16 </strong> </strong> </strong> </strong>
17 </p> </p> </p> </p>
18
readCookies.php
(1 of 2)
2003 Prentice Hall, Inc.
All rights reserved.
Outline88
19 <table border = <table border = <table border = <table border = "5""5""5""5" cellspacing = cellspacing = cellspacing = cellspacing = "0""0""0""0" cellpadding = cellpadding = cellpadding = cellpadding = "10""10""10""10">>>>
20 <?php<?php<?php<?php
21
22 // iterate through array $_COOKIE and print // iterate through array $_COOKIE and print // iterate through array $_COOKIE and print // iterate through array $_COOKIE and print
23 // name and value of each cookie // name and value of each cookie // name and value of each cookie // name and value of each cookie
24 foreachforeachforeachforeach ( $_COOKIE ( $_COOKIE ( $_COOKIE ( $_COOKIE asasasas $key = $key = $key = $key => $value )> $value )> $value )> $value )
25 print print print print( ( ( ( "<tr> "<tr> "<tr> "<tr>
26 <td bgcolor=<td bgcolor=<td bgcolor=<td bgcolor=\\\\"#F0E68C"#F0E68C"#F0E68C"#F0E68C\\\\">$key</td>">$key</td>">$key</td>">$key</td>
27 <td bgcolor=<td bgcolor=<td bgcolor=<td bgcolor=\\\\"#FFA500"#FFA500"#FFA500"#FFA500\\\\">$value</td>">$value</td>">$value</td>">$value</td>
28 </tr>"</tr>"</tr>"</tr>" ); ); ); );
29 ?>?>?>?>
30
31 </table </table </table </table>>>>
32 </body> </body> </body> </body>
33 </html></html></html></html>
readCookies.php
(2 of 2)
PHP creates array $_COOKIE which contains
all cookie values indexed by their names.
The foreach loop iterates through the $_COOKIE
array and prints the name and value of each cookie
in an XHTML table.
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.
Outline911 <!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.25: dynamicForm.php Fig. 26.25: dynamicForm.php Fig. 26.25: dynamicForm.php Fig. 26.25: dynamicForm.php -------->>>>
5 <!<!<!<!-------- Form for use with the form.php program Form for use with the form.php program Form for use with the form.php program Form for use with the form.php program -------->>>>
6
7 <html xmlns =<html xmlns =<html xmlns =<html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>
8 <head><head><head><head>
9 <title><title><title><title>Sample form to take user input in XHTMLSample form to take user input in XHTMLSample form to take user input in XHTMLSample form to take user input in XHTML</title></title></title></title>
10 </head></head></head></head>
11
12 <body><body><body><body>
13 <?php<?php<?php<?php
14 extract ( $_POST ); extract ( $_POST ); extract ( $_POST ); extract ( $_POST );
15 $iserror = $iserror = $iserror = $iserror = falsefalsefalsefalse;;;;
16
17 // array of book titles// array of book titles// array of book titles// array of book titles
18 $booklist = $booklist = $booklist = $booklist = arrayarrayarrayarray( ( ( ( "Internet and WWW How to Program 3e""Internet and WWW How to Program 3e""Internet and WWW How to Program 3e""Internet and WWW How to Program 3e",,,,
19 "C++ How to Program 4e""C++ How to Program 4e""C++ How to Program 4e""C++ How to Program 4e",,,,
20 "Java How to Program 5e""Java How to Program 5e""Java How to Program 5e""Java How to Program 5e",,,,
21 "XML How to Program 1e""XML How to Program 1e""XML How to Program 1e""XML How to Program 1e" ); ); ); );
22
dynamicForm.php
(1 of 9)
Build array of options for the form.
2003 Prentice Hall, Inc.
All rights reserved.
Outline92
23 // array of possible operating systems// array of possible operating systems// array of possible operating systems// array of possible operating systems
24 $systemlist = $systemlist = $systemlist = $systemlist = arrayarrayarrayarray( ( ( ( "Windows XP""Windows XP""Windows XP""Windows XP",,,,
25 "Windows 2000""Windows 2000""Windows 2000""Windows 2000",,,,
26 "Windows 98""Windows 98""Windows 98""Windows 98",,,,
27 "Linux""Linux""Linux""Linux",,,,
28 "Other""Other""Other""Other"););););
29
30 // array of name and alt values// array of name and alt values// array of name and alt values// array of name and alt values for the text input fields for the text input fields for the text input fields for the text input fields
31 $inputlist = $inputlist = $inputlist = $inputlist = arrayarrayarrayarray( ( ( ( "fname""fname""fname""fname" => => => => "First Name""First Name""First Name""First Name",,,,
32 "lname""lname""lname""lname" => => => => "Last Name""Last Name""Last Name""Last Name",,,,
33 "email""email""email""email" => => => => "Email""Email""Email""Email",,,,
34 "phone""phone""phone""phone" => => => => "Phone""Phone""Phone""Phone" ); ); ); );
35
36 ifififif ( isset ( $submit ) ) { ( isset ( $submit ) ) { ( isset ( $submit ) ) { ( isset ( $submit ) ) {
37 ifififif ( $fname == ( $fname == ( $fname == ( $fname == """""""" ) { ) { ) { ) {
38 $formerrors[ $formerrors[ $formerrors[ $formerrors[ "fnameerror""fnameerror""fnameerror""fnameerror" ] = ] = ] = ] = truetruetruetrue;;;;
39 $iserror = $iserror = $iserror = $iserror = truetruetruetrue;;;;
40 } } } }
41
42 ifififif ( $lname == ( $lname == ( $lname == ( $lname == """""""" ) { ) { ) { ) {
43 $formerrors[ $formerrors[ $formerrors[ $formerrors[ "l"l"l"lnameerror"nameerror"nameerror"nameerror" ] = ] = ] = ] = truetruetruetrue;;;;
44 $iserror = $iserror = $iserror = $iserror = truetruetruetrue;;;;
45 } } } }
46
dynamicForm.php
(2 of 9)
Check for errors or omissions in form field
input.
If the page is being loaded as a result of a form
submission, do error checking and then retrieve
information from the database.
2003 Prentice Hall, Inc.
All rights reserved.
Outline93
47 ifififif ( $email == ( $email == ( $email == ( $email == """""""" ) { ) { ) { ) {
48 $formerrors[ $formerrors[ $formerrors[ $formerrors[ "emailerror""emailerror""emailerror""emailerror" ] = ] = ] = ] = truetruetruetrue;;;;
49 $iserror = $iserror = $iserror = $iserror = truetruetruetrue;;;;
50 } } } }
51
52 ifififif ( !ereg( ( !ereg( ( !ereg( ( !ereg( "^"^"^"^\\\\([0([0([0([0----9]{3}9]{3}9]{3}9]{3}\\\\)[0)[0)[0)[0----9]{3}9]{3}9]{3}9]{3}----[0[0[0[0----9]{4}$"9]{4}$"9]{4}$"9]{4}$", $phone ) ) {, $phone ) ) {, $phone ) ) {, $phone ) ) {
53 $formerrors[ $formerrors[ $formerrors[ $formerrors[ """"phoneerror"phoneerror"phoneerror"phoneerror" ] = ] = ] = ] = truetruetruetrue;;;;
54 $iserror = $iserror = $iserror = $iserror = truetruetruetrue;;;;
55 } } } }
56
57 ifififif ( !$iserror ) { ( !$iserror ) { ( !$iserror ) { ( !$iserror ) {
58
59 // build INSERT query// build INSERT query// build INSERT query// build INSERT query
60 $query = $query = $query = $query = "INSERT INTO contacts ""INSERT INTO contacts ""INSERT INTO contacts ""INSERT INTO contacts " . . . .
61 "( LastName, FirstNa"( LastName, FirstNa"( LastName, FirstNa"( LastName, FirstName, Email, Phone, Book, OS ) "me, Email, Phone, Book, OS ) "me, Email, Phone, Book, OS ) "me, Email, Phone, Book, OS ) " . . . .
62 "VALUES ( '$lname', '$fname', '$email', ""VALUES ( '$lname', '$fname', '$email', ""VALUES ( '$lname', '$fname', '$email', ""VALUES ( '$lname', '$fname', '$email', " . . . .
63 "'""'""'""'" . quotemeta( $phone ) . . quotemeta( $phone ) . . quotemeta( $phone ) . . quotemeta( $phone ) . "', '$book', '$os' )""', '$book', '$os' )""', '$book', '$os' )""', '$book', '$os' )";;;;
64
65 // Connect to MySQL// Connect to MySQL// Connect to MySQL// Connect to MySQL
66 ifififif ( !( $database = my ( !( $database = my ( !( $database = my ( !( $database = mysql_connect( sql_connect( sql_connect( sql_connect( "localhost""localhost""localhost""localhost", , , ,
67 "httpd""httpd""httpd""httpd", , , , """""""" ) ) ) ) ) ) ) ) ) ) ) )
68 die( "Could not connect to database" ); die( "Could not connect to database" ); die( "Could not connect to database" ); die( "Could not connect to database" );
69
70 // open MailingList database// open MailingList database// open MailingList database// open MailingList database
71 ifififif ( !mysql_select_db( ( !mysql_select_db( ( !mysql_select_db( ( !mysql_select_db( "MailingList""MailingList""MailingList""MailingList", $database ) ), $database ) ), $database ) ), $database ) )
72 die( die( die( die( "Could not open MailingList database""Could not open MailingList database""Could not open MailingList database""Could not open MailingList database" ); ); ); );
dynamicForm.php
(3 of 9)
If there were no errors, query the MySQL
database.
2003 Prentice Hall, Inc.
All rights reserved.
Outline94
73
74 // execute query in MailingList database// execute query in MailingList database// execute query in MailingList database// execute query in MailingList database
75 ifififif ( !( $result = mysql_query( $query, $database ) ) ) { ( !( $result = mysql_query( $query, $database ) ) ) { ( !( $result = mysql_query( $query, $database ) ) ) { ( !( $result = mysql_query( $query, $database ) ) ) {
76 print( print( print( print( "Could not execute query! <br />""Could not execute query! <br />""Could not execute query! <br />""Could not execute query! <br />" ); ); ); );
77 die( mysql_error() ); die( mysql_error() ); die( mysql_error() ); die( mysql_error() );
78 } } } }
79
80 printprintprintprint( ( ( ( "<p>Hi"<p>Hi"<p>Hi"<p>Hi
81 <span style = 'color: blue'><span style = 'color: blue'><span style = 'color: blue'><span style = 'color: blue'>
82 <strong>$fname</strong></span>.<strong>$fname</strong></span>.<strong>$fname</strong></span>.<strong>$fname</strong></span>.
83 Thank you for completing the survey.<br />Thank you for completing the survey.<br />Thank you for completing the survey.<br />Thank you for completing the survey.<br />
84
85 You have You have You have You have been added to thebeen added to thebeen added to thebeen added to the
86 <span style = 'color: blue'><span style = 'color: blue'><span style = 'color: blue'><span style = 'color: blue'>
87 <strong>$book</strong></span><strong>$book</strong></span><strong>$book</strong></span><strong>$book</strong></span>
88 mailing list.mailing list.mailing list.mailing list.
89 </p></p></p></p>
90 <strong>The following information has been saved<strong>The following information has been saved<strong>The following information has been saved<strong>The following information has been saved
91 in our database:</strong><br />in our database:</strong><br />in our database:</strong><br />in our database:</strong><br />
92
93 <table border = '0' cellpadding = '0' cellspacing = '10'><table border = '0' cellpadding = '0' cellspacing = '10'><table border = '0' cellpadding = '0' cellspacing = '10'><table border = '0' cellpadding = '0' cellspacing = '10'>
94 <tr><tr><tr><tr>
95 <td bgcolor = '#ffffaa'>Name</td><td bgcolor = '#ffffaa'>Name</td><td bgcolor = '#ffffaa'>Name</td><td bgcolor = '#ffffaa'>Name</td>
96 <td bgcolor = '#fff<td bgcolor = '#fff<td bgcolor = '#fff<td bgcolor = '#ffffbb'>Email</td>fbb'>Email</td>fbb'>Email</td>fbb'>Email</td>
97 <td bgcolor = '#ffffcc'>Phone</td><td bgcolor = '#ffffcc'>Phone</td><td bgcolor = '#ffffcc'>Phone</td><td bgcolor = '#ffffcc'>Phone</td>
dynamicForm.php
(4 of 9)
2003 Prentice Hall, Inc.
All rights reserved.
Outline95
98 <td bgcolor = '#ffffdd'>OS</td><td bgcolor = '#ffffdd'>OS</td><td bgcolor = '#ffffdd'>OS</td><td bgcolor = '#ffffdd'>OS</td>
99 </tr></tr></tr></tr>
100 <tr><tr><tr><tr>
101
102 <!<!<!<!-------- print each form field’s value print each form field’s value print each form field’s value print each form field’s value -------->>>>
103 <td>$fname $lname</td><td>$fname $lname</td><td>$fname $lname</td><td>$fname $lname</td>
104 <td>$email</td><td>$email</td><td>$email</td><td>$email</td>
105 <td>$phone</td><td>$phone</td><td>$phone</td><td>$phone</td>
106 <td>$os</td><td>$os</td><td>$os</td><td>$os</td>
107 </tr></table></tr></table></tr></table></tr></table>
108
109 <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
110 <div style = 'font<div style = 'font<div style = 'font<div style = 'font----size: 10pt; textsize: 10pt; textsize: 10pt; textsize: 10pt; text----align: center'>align: center'>align: center'>align: center'>
111 <div style =<div style =<div style =<div style = 'font 'font 'font 'font----size : 18pt'>size : 18pt'>size : 18pt'>size : 18pt'>
112 <a href = 'formDatabase.php'><a href = 'formDatabase.php'><a href = 'formDatabase.php'><a href = 'formDatabase.php'>
113 Click here to view entire database.</a></div>Click here to view entire database.</a></div>Click here to view entire database.</a></div>Click here to view entire database.</a></div>
114 This is only a sample form. This is only a sample form. This is only a sample form. This is only a sample form.
115 You have not been added to a mailing list.You have not been added to a mailing list.You have not been added to a mailing list.You have not been added to a mailing list.
116 </div></body></html>"</div></body></html>"</div></body></html>"</div></body></html>" ); ); ); );
117 die(); die(); die(); die();
118 } } } }
119 } } } }
120
121 printprintprintprint( ( ( ( "<h1>This is a sample registration form.</h1>"<h1>This is a sample registration form.</h1>"<h1>This is a sample registration form.</h1>"<h1>This is a sample registration form.</h1>
122 Please fill in all fields and click Register."Please fill in all fields and click Register."Please fill in all fields and click Register."Please fill in all fields and click Register." ); ); ); );
dynamicForm.php
(5 of 9)
Halt the script so the form-generation code
does not execute.
2003 Prentice Hall, Inc.
All rights reserved.
Outline96
123
124 ifififif ( $iserror ) { ( $iserror ) { ( $iserror ) { ( $iserror ) {
125 printprintprintprint( ( ( ( "<br /><span style = 'color : red'>"<br /><span style = 'color : red'>"<br /><span style = 'color : red'>"<br /><span style = 'color : red'>
126 Fields with * need to be filled in properly.</span>"Fields with * need to be filled in properly.</span>"Fields with * need to be filled in properly.</span>"Fields with * need to be filled in properly.</span>" ); ); ); );
127 } } } }
128
129 printprintprintprint( ( ( ( "<!"<!"<!"<!-------- post form data to form.php post form data to form.php post form data to form.php post form data to form.php -------->>>>
130 <form method = 'post' action = 'dynamicform.php'><form method = 'post' action = 'dynamicform.php'><form method = 'post' action = 'dynamicform.php'><form method = 'post' action = 'dynamicform.php'>
131 <img src = 'images/user.gif' alt = 'User' /><br /><img src = 'images/user.gif' alt = 'User' /><br /><img src = 'images/user.gif' alt = 'User' /><br /><img src = 'images/user.gif' alt = 'User' /><br />
132 <span style = 'color: blue'><span style = 'color: blue'><span style = 'color: blue'><span style = 'color: blue'>
133 Please fill outPlease fill outPlease fill outPlease fill out the fields below.<br /> the fields below.<br /> the fields below.<br /> the fields below.<br />
134 </span></span></span></span>
135
136 <!<!<!<!-------- create four text boxes for user input create four text boxes for user input create four text boxes for user input create four text boxes for user input -------->">">">" ); ); ); );
137 foreachforeachforeachforeach ( $inputlist ( $inputlist ( $inputlist ( $inputlist asasasas $inputname => $inputalt ) { $inputname => $inputalt ) { $inputname => $inputalt ) { $inputname => $inputalt ) {
138 $inputtext = $inputvalues[ $inputname ]; $inputtext = $inputvalues[ $inputname ]; $inputtext = $inputvalues[ $inputname ]; $inputtext = $inputvalues[ $inputname ];
139
140 printprintprintprint( ( ( ( "<img src = 'images/$inputname.gif'"<img src = 'images/$inputname.gif'"<img src = 'images/$inputname.gif'"<img src = 'images/$inputname.gif'
141 alt = '$inputalt' /><input type = 'text'alt = '$inputalt' /><input type = 'text'alt = '$inputalt' /><input type = 'text'alt = '$inputalt' /><input type = 'text'
142 name = '$inputname' value = '"name = '$inputname' value = '"name = '$inputname' value = '"name = '$inputname' value = '" . $$inputname . . $$inputname . . $$inputname . . $$inputname . "' />""' />""' />""' />" ); ); ); );
143
144 ifififif ( $formerrors[ ( $formerrors[ ( $formerrors[ ( $formerrors[ ( $inputname ). ( $inputname ). ( $inputname ). ( $inputname )."error""error""error""error" ] == ] == ] == ] == truetruetruetrue ) ) ) )
145 printprintprintprint( ( ( ( "<span style = 'color : red'>*</span>""<span style = 'color : red'>*</span>""<span style = 'color : red'>*</span>""<span style = 'color : red'>*</span>" ); ); ); );
146
147 printprintprintprint( ( ( ( "<br />""<br />""<br />""<br />" ); ); ); );
148 } } } }
dynamicForm.php
(6 of 9)
If the form input contained errors, place a red
asterisk (*) next to the text field.
Fill in the forms using $$variable syntax.
2003 Prentice Hall, Inc.
All rights reserved.
Outline97
149
150 printprintprintprint( ( ( ( "<span style = 'font"<span style = 'font"<span style = 'font"<span style = 'font----size : 10pt"size : 10pt"size : 10pt"size : 10pt" ); ); ); );
151
152 ifififif ( $formerrors[ ( $formerrors[ ( $formerrors[ ( $formerrors[ "phoneerror""phoneerror""phoneerror""phoneerror" ] ) ] ) ] ) ] )
153 printprintprintprint( ( ( ( "; color : red""; color : red""; color : red""; color : red" ); ); ); );
154
155 printprintprintprint( ( ( ( "'>Must be in the form (555)555"'>Must be in the form (555)555"'>Must be in the form (555)555"'>Must be in the form (555)555----5555555555555555
156 </span><br /><b</span><br /><b</span><br /><b</span><br /><br />r />r />r />
157
158 <img src = 'images/downloads.gif'<img src = 'images/downloads.gif'<img src = 'images/downloads.gif'<img src = 'images/downloads.gif'
159 alt = 'Publications' /><br />alt = 'Publications' /><br />alt = 'Publications' /><br />alt = 'Publications' /><br />
160
161 <span style = 'color: blue'><span style = 'color: blue'><span style = 'color: blue'><span style = 'color: blue'>
162 Which book would you like information about?Which book would you like information about?Which book would you like information about?Which book would you like information about?
163 </span><br /></span><br /></span><br /></span><br />
164
165 <!<!<!<!-------- create drop create drop create drop create drop----down list containing book names down list containing book names down list containing book names down list containing book names -------->>>>
166 <select name = 'book'>"<select name = 'book'>"<select name = 'book'>"<select name = 'book'>" ); ); ); );
167
168 foreachforeachforeachforeach ( $booklist ( $booklist ( $booklist ( $booklist asasasas $currbook ) { $currbook ) { $currbook ) { $currbook ) {
169 printprintprintprint( ( ( ( "<option""<option""<option""<option" ); ); ); );
170
171 ifififif ( ( $currbook == $book ) ) ( ( $currbook == $book ) ) ( ( $currbook == $book ) ) ( ( $currbook == $book ) )
172 printprintprintprint( ( ( ( " selected = 'true'"" selected = 'true'"" selected = 'true'"" selected = 'true'" ); ); ); );
173
dynamicForm.php
(7 of 9)
Make sure the correct book is selected in the
dropdown box.
2003 Prentice Hall, Inc.
All rights reserved.
Outline98
174 printprintprintprint( ( ( ( ">$currbook</option>"">$currbook</option>"">$currbook</option>"">$currbook</option>" ); ); ); );
175 } } } }
176
177 printprintprintprint( ( ( ( "</select><br /><br />"</select><br /><br />"</select><br /><br />"</select><br /><br />
178 <img src = 'images/os.gif' alt = 'Operating System' /><img src = 'images/os.gif' alt = 'Operating System' /><img src = 'images/os.gif' alt = 'Operating System' /><img src = 'images/os.gif' alt = 'Operating System' />
179 <br /><span style = 'color: blue'><br /><span style = 'color: blue'><br /><span style = 'color: blue'><br /><span style = 'color: blue'>
180 Which operating system are you currently using?Which operating system are you currently using?Which operating system are you currently using?Which operating system are you currently using?
181 <br /></span><br /></span><br /></span><br /></span>
182
183 <!<!<!<!-------- create five radio buttons create five radio buttons create five radio buttons create five radio buttons -------->">">">" ); ); ); );
184
185 $counter = $counter = $counter = $counter = 0000;;;;
186
187 foreachforeachforeachforeach ( $systemlist ( $systemlist ( $systemlist ( $systemlist asasasas $currsystem ) { $currsystem ) { $currsystem ) { $currsystem ) {
188 prinprinprinprintttt( ( ( ( "<input type = 'radio' name = 'os'"<input type = 'radio' name = 'os'"<input type = 'radio' name = 'os'"<input type = 'radio' name = 'os'
189 value = '$currsystem'"value = '$currsystem'"value = '$currsystem'"value = '$currsystem'" ); ); ); );
190
191 ifififif ( $currsystem == $os ) ( $currsystem == $os ) ( $currsystem == $os ) ( $currsystem == $os ) printprintprintprint( ( ( ( "checked = 'checked'""checked = 'checked'""checked = 'checked'""checked = 'checked'" ); ); ); );
192 ifififif ( $iserror && $counter == ( $iserror && $counter == ( $iserror && $counter == ( $iserror && $counter == 0000 ) ) ) ) printprintprintprint( ( ( ( "checked = 'checked'""checked = 'checked'""checked = 'checked'""checked = 'checked'" ); ); ); );
193
194 printprintprintprint( ( ( ( " />$currsystem"" />$currsystem"" />$currsystem"" />$currsystem" ); ); ); );
195
196 ifififif ( $counter == ( $counter == ( $counter == ( $counter == 2222 ) ) ) ) printprintprintprint( ( ( ( "<br />""<br />""<br />""<br />" ); ); ); );
197 $counter++; $counter++; $counter++; $counter++;
198 } } } }
199
dynamicForm.php
(8 of 9)
Make sure the correct OS is checked in the
checkbox.
2003 Prentice Hall, Inc.
All rights reserved.
Outline99
200 printprintprintprint( ( ( ( "<!"<!"<!"<!-------- create a submit button create a submit button create a submit button create a submit button -------->>>>
201 <br /> <br /> <br /> <br />
202 <input type = 'submit' name = 'submit' value = 'Register' /><input type = 'submit' name = 'submit' value = 'Register' /><input type = 'submit' name = 'submit' value = 'Register' /><input type = 'submit' name = 'submit' value = 'Register' />
203 </form></body></html>"</form></body></html>"</form></body></html>"</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.
Outline1021 <!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC<!DOCTYPE html PUBLIC """"----//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1----transitional.dtd"transitional.dtd"transitional.dtd"transitional.dtd">>>>
3
4 <!<!<!<!-------- Fig. 26.26: formDatabase.php Fig. 26.26: formDatabase.php Fig. 26.26: formDatabase.php Fig. 26.26: formDatabase.php -------->>>>
5 <!<!<!<!-------- Program to query a database and Program to query a database and Program to query a database and Program to query a database and -------->>>>
6 <!<!<!<!-------- send send send send results to the client. results to the client. results to the client. results to the client. -------->>>>
7
8 <html xmlns =<html xmlns =<html xmlns =<html xmlns = "http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml""http://www.w3.org/1999/xhtml">>>>
9 <head><head><head><head>
10 <title><title><title><title>Search ResultsSearch ResultsSearch ResultsSearch Results</title></title></title></title>
11 </head></head></head></head>
12
13 <body style =<body style =<body style =<body style = "font"font"font"font----family: arial, sansfamily: arial, sansfamily: arial, sansfamily: arial, sans----serif"serif"serif"serif"
14 style =style =style =style = "backg"backg"backg"backgroundroundroundround----color: #F0E68C"color: #F0E68C"color: #F0E68C"color: #F0E68C">>>>
15 <?php<?php<?php<?php
16
17 extract( $_POST ); extract( $_POST ); extract( $_POST ); extract( $_POST );
18
19 // build SELECT query// build SELECT query// build SELECT query// build SELECT query
20 $query = $query = $query = $query = "SELECT * FROM contacts""SELECT * FROM contacts""SELECT * FROM contacts""SELECT * FROM contacts";;;;
21
22 // Connect to MySQL// Connect to MySQL// Connect to MySQL// Connect to MySQL
23 ifififif ( !( $databa ( !( $databa ( !( $databa ( !( $database = mysql_connect( se = mysql_connect( se = mysql_connect( se = mysql_connect( "localhost""localhost""localhost""localhost", , , ,
24 "httpd""httpd""httpd""httpd", , , , """""""" ) ) ) ) ) ) ) ) ) ) ) )
25 die( die( die( die( "Could not connect to database""Could not connect to database""Could not connect to database""Could not connect to database" ); ); ); );
formDatabase.php
(1 of 3)
Build the query string.
2003 Prentice Hall, Inc.
All rights reserved.
Outline103
26
27 // open MailingList database// open MailingList database// open MailingList database// open MailingList database
28 ifififif ( !mysql_select_db( ( !mysql_select_db( ( !mysql_select_db( ( !mysql_select_db( "MailingList""MailingList""MailingList""MailingList", $database ) ), $database ) ), $database ) ), $database ) )
29 die( die( die( die( "Could not open MailingList database""Could not open MailingList database""Could not open MailingList database""Could not open MailingList database" ); ); ); );
30
31 // query MailingList database// query MailingList database// query MailingList database// query MailingList database
32 ifififif ( !( $result = mysql_query( $query, $database ) ) ) { ( !( $result = mysql_query( $query, $database ) ) ) { ( !( $result = mysql_query( $query, $database ) ) ) { ( !( $result = mysql_query( $query, $database ) ) ) {
33 printprintprintprint( ( ( ( "Could not execute query! <br />""Could not execute query! <br />""Could not execute query! <br />""Could not execute query! <br />" ); ); ); );
34 die( mysql_error() ); die( mysql_error() ); die( mysql_error() ); die( mysql_error() );
35 } } } }
36 ?>?>?>?>
37
38 <h3 style =<h3 style =<h3 style =<h3 style = "color: blue""color: blue""color: blue""color: blue">>>>
39 Mailing Mailing Mailing Mailing List ContactsList ContactsList ContactsList Contacts</h3></h3></h3></h3>
40
41 <table border =<table border =<table border =<table border = "1""1""1""1" cellpadding =cellpadding =cellpadding =cellpadding = "3""3""3""3" cellspacing =cellspacing =cellspacing =cellspacing = "2""2""2""2"
42 style =style =style =style = "background"background"background"background----color: #ADD8E6"color: #ADD8E6"color: #ADD8E6"color: #ADD8E6">>>>
43
44 <tr><tr><tr><tr>
45 <td><td><td><td>IDIDIDID</td></td></td></td>
46 <td><td><td><td>Last NameLast NameLast NameLast Name</td></td></td></td>
47 <td><td><td><td>First NameFirst NameFirst NameFirst Name</td></td></td></td>
48 <td><td><td><td>EEEE----mail Addressmail Addressmail Addressmail Address</td></td></td></td>
49 <td><td><td><td>Phone NumberPhone NumberPhone NumberPhone Number</td></td></td></td>
50 <td><td><td><td>BookBookBookBook</td></td></td></td>
formDatabase.php
(2 of 3)
2003 Prentice Hall, Inc.
All rights reserved.
Outline104
51 <td><td><td><td>Operating SystemOperating SystemOperating SystemOperating System</td></td></td></td>
52 </tr></tr></tr></tr>
53 <?php<?php<?php<?php
54
55 // fetch each record in result set// fetch each record in result set// fetch each record in result set// fetch each record in result set
56 forforforfor ( $counter = ( $counter = ( $counter = ( $counter = 0000; ; ; ;
57 $row = mysql_fetch_row( $result ); $row = mysql_fetch_row( $result ); $row = mysql_fetch_row( $result ); $row = mysql_fetch_row( $result );
58 $counter++ ){ $counter++ ){ $counter++ ){ $counter++ ){
59
60 // build table to display results// build table to display results// build table to display results// build table to display results
61 printprintprintprint( ( ( ( "<tr>""<tr>""<tr>""<tr>" ); ); ); );
62
63 foreachforeachforeachforeach ( $row ( $row ( $row ( $row asasasas $key => $value ) $key => $value ) $key => $value ) $key => $value )
64 printprintprintprint( ( ( ( "<td>$value</td>""<td>$value</td>""<td>$value</td>""<td>$value</td>" ); ); ); );
65
66 printprintprintprint( ( ( ( "</tr>""</tr>""</tr>""</tr>" ); ); ); );
67 } } } }
68
69 mysql_close( $database ); mysql_close( $database ); mysql_close( $database ); mysql_close( $database );
70 ?>?>?>?>
71
72 </table></table></table></table>
73
74 </body></body></body></body>
75 </html></html></html></html>
formDatabase.php
(3 of 3)
Dynamically create a table
containing each mailing list
member.
Retrieve each mailing list
member record from the
database.
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 PrecedenceOperator Type Associativity new constructor none
[] subscript right to left
~ ! ++ -- - @
bitwise not not increment decrement unary negative error control
right to left
* / %
multiplication division modulus
left to right
+ - .
addition subtraction concatenation
left to right
<< >>
bitwise shift left bitwise shift right
left to right
< > <= >=
less than greater than less than or equal greater than or equal
none
== != === !==
equal not equal identical not identical
none
Fig. 26.27 PHP operator precedence and associativity.
2003 Prentice Hall, Inc. All rights reserved.
107
26.10 Operator PrecedenceOperator 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 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
left to right
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.