Transcript 1 - Pusan

1
23
PHP
 2008 Pearson Education, Inc. All rights reserved.
2
Conversion for me was not a Damascus Road
experience. I slowly moved into a intellectual
acceptance of what my intuition had always known.
— Madeleine L’Engle
Be careful when reading health books;
you may die of a misprint.
— Mark Twain
 2008 Pearson Education, Inc. All rights reserved.
3
Reckoners without their host must reckon twice.
— John Heywood
There was a door to which I found no key;
There was the veil through which I might not see.
— Omar Khayyam
 2008 Pearson Education, Inc. All rights reserved.
4
OBJECTIVES
In this chapter you will learn:
 To manipulate data of various types.
 To use operators, arrays and control statements.
 To use regular expressions to search for patterns.
 To construct programs that process form data.
 To store data on the client using cookies.
 To create programs that interact with MySQL
databases.
 2008 Pearson Education, Inc. All rights reserved.
5
23.1 Introduction
23.2 PHP Basics
23.3 String Processing and Regular Expressions
23.3.1 Comparing Strings
23.3.2 Regular Expressions
23.4 Form Processing and Business Logic
23.5 Connecting to a Database
23.6 Using Cookies
23.7 Dynamic Content
23.8 Operator Precedence Chart
23.9 Wrap-Up
23.10 Web Resources
 2008 Pearson Education, Inc. All rights reserved.
6
23.1 Introduction
• PHP, or PHP: Hypertext Preprocessor, has
become one of the most popular server-side
scripting languages for creating dynamic web
pages.
• PHP is open source and platform independent—
implementations exist for all major UNIX, Linux,
Mac and Windows operating systems. PHP also
supports a large number of databases.
 2008 Pearson Education, Inc. All rights reserved.
7
23.2 PHP Basics
• The power of the web resides not only in serving content to users, but
also in responding to requests from users and generating web pages
with dynamic content.
• PHP code is embedded directly into XHTML documents, though these
script segments are interpreted by a server before being delivered to
the client.
• PHP script file names end with .php.
• Although PHP can be used from the command line, a web server is
necessary to take full advantage of the scripting language.
• In PHP, code is inserted between the scripting delimiters <?php and
?>. PHP code can be placed anywhere in XHTML markup, as long as
the code is enclosed in these delimiters.
 2008 Pearson Education, Inc. All rights reserved.
8
23.2 PHP Basics (Cont.)
• Variables are preceded by a $ and are created the first time they are
encountered.
• PHP statements terminate with a semicolon (;).
• Single-line comments which begin with two forward slashes (//) or a
pound sign (#). Text to the right of the delimiter is ignored by the
interpreter. Multiline comments begin with delimiter /* and end with
delimiter */.
• When a variable is encountered inside a double-quoted ("") string,
PHP interpolates the variable. In other words, PHP inserts the
variable’s value where the variable name appears in the string.
• All operations requiring PHP interpolation execute on the server
before the XHTML document is sent to the client.
• PHP variables are loosely typed—they can contain different types of
data at different times.
 2008 Pearson Education, Inc. All rights reserved.
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
9
Outline
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
<!-- Fig. 23.1: first.php -->
6
<!-- Simple PHP program. -->
7
<html xmlns = "http://www.w3.org/1999/xhtml">
8
<?php
9
Delimiters
enclosing PHP
script
first.php
$name = "Harvey"; // declaration and initialization
10 ?><!-- end PHP script -->
11
12
<head>
<title>Using PHP document</title>
13
</head>
14
<body style = "font-size: 2em">
15
Declares and
initializes a PHP
variable
<p>
<strong>
16
17
<!-- print variable name’s value -->
18
Welcome to PHP, <?php print( "$name" ); ?>!
</strong>
19
20
</p>
21
</body>
Interpolates the variable
so that its value will be
output to the XHTML
document
22 </html>
 2008 Pearson Education,
Inc. All rights reserved.
10
Common Programming Error 23.1
Failing to precede a variable name
with a $ is a syntax error.
 2008 Pearson Education, Inc. All rights reserved.
11
Common Programming Error 23.2
Variable names in PHP are case sensitive.
Failure to use the proper mixture of cases to
refer to a variable will result in a logic error,
since the script will create a new variable for
any name it doesn’t recognize as a previously
used variable.
 2008 Pearson Education, Inc. All rights reserved.
12
Common Programming Error 23.3
Forgetting to terminate a statement
with a semicolon (;) is a syntax error.
 2008 Pearson Education, Inc. All rights reserved.
13
Type
Description
int, integer
Whole numbers (i.e., numbers without a decimal point).
float, double, real
string
Real numbers (i.e., numbers containing a decimal point).
bool, boolean
array
True or false.
object
Group of associated data and methods.
resource
An external source—usually information from a database.
NULL
No value.
Text enclosed in either single ('') or double ("") quotes.
[Note: Using double quotes allows PHP to recognize
more escape sequences.]
Group of elements.
Fig. 23.2 | PHP types.
 2008 Pearson Education, Inc. All rights reserved.
14
23.2 PHP Basics (Cont.)
• Type conversions can be performed using function settype. This function
takes two arguments—a variable whose type is to be changed and the
variable’s new type.
• Variables are automatically converted to the type of the value they are
assigned.
• Function gettype returns the current type of its argument.
• Calling function settype can result in loss of data. For example, doubles are
truncated when they are converted to integers.
• When converting from a string to a number, PHP uses the value of the
number that appears at the beginning of the string. If no number appears at
the beginning, the string evaluates to 0.
• Another option for conversion between types is casting (or type casting).
Casting does not change a variable’s content—it creates a temporary copy of
a variable’s value in memory.
• The concatenation operator (.) combines multiple strings.
• A print statement split over multiple lines prints all the data that is enclosed
in its parentheses.
 2008 Pearson Education, Inc. All rights reserved.
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
15
Outline
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
<!-- Fig. 23.3: data.php -->
6
<!-- Data type conversion. -->
7
<html xmlns = "http://www.w3.org/1999/xhtml">
8
9
(1 of 3)
<head>
<title>Data type conversion</title>
10
</head>
11
<body>
12
data.php
<?php
13
// declare a string, double and integer
14
$testString = "3.5 seconds";
15
$testDouble = 79.2;
16
$testInteger = 12;
17
?><!-- end PHP script -->
Automatically declares a string
Automatically declares a double
Automatically declares an integer
18
19
<!-- print each variable’s value and type -->
20
<?php
21
22
Outputs the type of
$testString
print( "$testString is a(n) " . gettype( $testString )
. "<br />" );
 2008 Pearson Education,
Inc. All rights reserved.
23
print( "$testDouble is a(n) " . gettype( $testDouble )
. "<br />" );
24
25
Outline
print( "$testInteger is a(n) " . gettype( $testInteger)
26
. "<br />" );
27
?><!-- end PHP script -->
28
<br />
29
converting to other data types:<br />
30
<?php
data.php
(2 of 3)
31
// call function settype to convert variable
32
// testString to different data types
33
print( "$testString" );
34
settype( $testString, "double" );
35
print( " as a double is $testString <br />" );
36
print( "$testString" );
37
settype( $testString, "integer" );
38
print( " as an integer is $testString <br />" );
39
settype( $testString, "string" );
40
print( "converting back to a string results in
41
16
Modifies $testString
to be a double
Modifies $testString
to be an integer
Modifies $testString
to be a string
$testString <br /><br />" );
42
 2008 Pearson Education,
Inc. All rights reserved.
43
// use type casting to cast variables to a different type
44
$data = "98.6 degrees";
45
print( "before casting, $data is a " .
46
gettype( $data ) . "<br /><br />" );
47
print( "using type casting instead: <br />
48
as a double: " . (double) $data .
49
"<br />as an integer: " . (integer) $data );
Outline
data.php
(3 of 3)
gettype( $data ) );
51
53
Temporarily casts
$data as a double
and an integer
print( "<br /><br />after casting, $data is a " .
50
52
17
?><!-- end PHP script -->
</body>
Concatenation
54 </html>
 2008 Pearson Education,
Inc. All rights reserved.
18
Error-Prevention Tip 23.1
Function print can be used to display
the value of a variable at a particular
point during a program’s execution.
This is often helpful in debugging a script.
 2008 Pearson Education, Inc. All rights reserved.
19
23.2 PHP Basics (Cont.)
• Function define creates a named constant. It takes two
arguments—the name and value of the constant. An
optional third argument accepts a boolean value that
specifies whether the constant is case insensitive—
constants are case sensitive by default.
• Uninitialized variables have the value undef, which has
different values, depending on its context. In a numeric
context, it evaluates to 0. In a string context, it evaluates
to an empty string ("").
• Keywords may not be used as identifiers.
 2008 Pearson Education, Inc. All rights reserved.
20
Common Programming Error 23.4
Assigning a value to a constant after
it is declared is a syntax error.
 2008 Pearson Education, Inc. All rights reserved.
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
<!-- Fig. 23.4: operators.php -->
6
7
8
<!-- Using arithmetic operators. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
9
10
<title>Using arithmetic operators</title>
</head>
11
<body>
12
Outline
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
operators.php
(1 of 3)
<?php
13
14
$a = 5;
print( "The value of variable a is $a <br />" );
15
16
// define constant VALUE
17
define( "VALUE", 5 );
18
19
20
21
// add constant VALUE to variable $a
$a = $a + VALUE;
print( "Variable a after adding constant VALUE
22
21
Creates the named
constant VALUE with a
value of 5
is $a <br />" );
Equivalent to $a = $a * 2
23
24
25
// multiply variable $a by 2
$a *= 2;
26
print( "Multiplying variable a by 2 yields $a <br />" );
27
 2008 Pearson Education,
Inc. All rights reserved.
28
29
30
// test if variable $a is less than 50
if ( $a < 50 )
print( "Variable a is less than 50 <br />" );
31
32
33
// add 40 to variable $a
$a += 40;
34
35
print( "Variable a after adding 40 is $a <br />" );
36
37
38
39
// test if variable $a is 50 or less
with a variable
if ( $a < 51 )
print( "Variable a is still 50 or less<br />" );
40
41
42
// test if variable $a is between 50 and 100, inclusive
elseif ( $a < 101 )
print( "Variable a is now between 50 and 100,
Uses a comparison operator
and an integer
22
Outline
operators.php
(2 of 3)
inclusive<br />" );
43
44
45
else
print( "Variable a is now greater than 100 <br />" );
46
47
// print an uninitialized variable
48
49
50
print( "Using a variable before initializing:
$nothing <br />" ); // nothing evaluates to ""
51
52
// add constant VALUE to an uninitialized variable
$test = $num + VALUE; // num evaluates to 0
Uninitialized variable
$num evaluates to 0
 2008 Pearson Education,
Inc. All rights reserved.
print( "An uninitialized variable plus constant
53
Outline
VALUE yields $test <br />" );
54
23
55
$str is converted to an
integer for this operation
56
// add a string to an integer
57
$str = "3 dollars";
58
$a += $str;
59
print( "Adding a string to variable a yields $a <br />" );
60
61
?><!-- end PHP script -->
operators.php
(3 of 3)
</body>
62 </html>
 2008 Pearson Education,
Inc. All rights reserved.
24
Error-Prevention Tip 23.2
Initialize variables before they are used
to avoid subtle errors. For example,
multiplying a number by an uninitialized
variable results in 0.
 2008 Pearson Education, Inc. All rights reserved.
25
PHP keywords
abstract
and
array
as
break
case
catch
__CLASS__
die
do
echo
else
elseif
empty
enddeclare
endfor
exit
extends
__FILE__
file
final
for
foreach
__FUNCTION__
interface
isset
__LINE__
line
list
__METHOD__
method
new
require
require_once
return
static
switch
throw
try
unset
class
clone
endforeach
endif
function
global
or
php_user_filter
use
var
const
continue
declare
default
endswitch
endwhile
eval
exception
if
implements
include
include_once
print
private
protected
public
while
xor
Fig. 23.5 | PHP keywords.
 2008 Pearson Education, Inc. All rights reserved.
26
23.2 PHP Basics (Cont.)
• PHP provides the capability to store data in arrays. Arrays are
divided into elements that behave as individual variables. Array
names, like other variables, begin with the $ symbol.
• Individual array elements are accessed by following the array’s
variable name with an index enclosed in square brackets ([]).
• If a value is assigned to an array that does not exist, then the array is
created. Likewise, assigning a value to an element where the index is
omitted appends a new element to the end of the array.
• Function count returns the total number of elements in the array.
• Function array creates an array that contains the arguments passed
to it. The first item in the argument list is stored as the first array
element (index 0), the second item is stored as the second array
element and so on.
 2008 Pearson Education, Inc. All rights reserved.
27
23.2 PHP Basics (Cont.)
• Arrays with nonnumeric indices are called associative arrays. You can
create an associative array using the operator =>, where the value to
the left of the operator is the array index and the value to the right is
the element’s value.
• PHP provides functions for iterating through the elements of an
array. Each array has a built-in internal pointer, which points to the
array element currently being referenced. Function reset sets the
internal pointer to the first array element. Function key returns the
index of the element currently referenced by the internal pointer, and
function next moves the internal pointer to the next element.
• The foreach statement, designed for iterating through arrays, starts
with the array to iterate through, followed by the keyword as,
followed by two variables—the first is assigned the index of the
element and the second is assigned the value of that index’s element.
(If only one variable is listed after as, it is assigned the value of the
array element.)
 2008 Pearson Education, Inc. All rights reserved.
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
3
4
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
5 <!-- Fig. 23.6: arrays.php -->
6 <!-- Array manipulation. -->
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
<head>
9
<title>Array manipulation</title>
10
</head>
11
<body>
12
13
14
28
Outline
arrays.php
(1 of 4)
Automatically creates
array $first
<?php
Sets the first element of array
// create array first
print( "<strong>Creating the first array</strong><br />" );$first to the string “zero”
15
16
17
$first[ 0 ] = "zero";
$first[ 1 ] = "one";
$first[ 2 ] = "two";
18
19
20
21
22
23
$first[] = "three";
“three” is appended to
the end of array $first
// print each element’s index and value
for ( $i = 0; $i < count( $first ); $i++ )
print( "Element $i is $first[$i] <br />" );
Returns the number of
elements in the array
 2008 Pearson Education,
Inc. All rights reserved.
24
25
print( "<br /><strong>Creating the second array
29
Outline
</strong><br />" );
26
27
// call function array to create array second
28
$second = array( "zero", "one", "two", "three" );
arrays.php
29
30
31
for ( $i = 0; $i < count( $second ); $i++ )
(2 of 4)
print( "Element $i is $second[$i] <br />" );
32
33
34
Function array creates
array $second with its
arguments as elements
print( "<br /><strong>Creating the third array
</strong><br />" );
35
36
// assign values to entries using nonnumeric indices
37
$third[ "Amy" ] = 21;
38
$third[ "Bob" ] = 18;
39
$third[ "Carol" ] = 23;
Creates associative
array $third
40
41
// iterate through the array elements and print each
42
// element’s name and value
43
for ( reset( $third ); $element = key( $third ); next( $third ) )
44
print( "$element is $third[$element] <br />" );
45
Sets the internal
pointer to the first
array element in
$third
Returns the index
of the element
being pointed to
Moves the internal
pointer to the next
element and returns
it
 2008 Pearson Education,
Inc. All rights reserved.
print( "<br /><strong>Creating the fourth array
46
30
Outline
</strong><br />" );
47
48
49
// call function array to create array fourth using
50
// string indices
51
$fourth = array(
arrays.php
52
"January"
=> "first",
"February" => "second",
53
"March"
=> "third",
"April"
=> "fourth",
54
"May"
=> "fifth",
"June"
=> "sixth",
55
"July"
=> "seventh", "August"
56
"September" => "ninth",
57
"November"
58
);
"October"
=> "eighth",
=> "tenth",
=> "eleventh","December" => "twelfth"
59
60
// print each element’s name and value
61
foreach ( $fourth as $element => $value )
64
Uses operator => to
initialize the element
with index
“January” to have
value “first”
print( "$element is the $value month <br />" );
62
63
(3 of 4)
?><!-- end PHP script -->
</body>
65 </html>
Iterates through
each element in
array $fourth
Stores
the index
of the
element
Stores the value
of the element
 2008 Pearson Education,
Inc. All rights reserved.
31
Outline
arrays.php
(4 of 4)
 2008 Pearson Education,
Inc. All rights reserved.
32
23.3 String Processing and Regular
Expressions
• A regular expression is a series of characters used for
pattern-matching templates in strings, text files and
databases.
• Many string-processing tasks can be accomplished using
the equality and relational operators (==, !=, <, <=, > and
>=).
• Function strcmp compares two strings. The function
returns -1 if the first string alphabetically precedes the
second string, 0 if the strings are equal, and 1 if the first
string alphabetically follows the second.
 2008 Pearson Education, Inc. All rights reserved.
1
2
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3
4
5
<!-- Fig. 23.7: compare.php -->
6
7
8
<!-- Using the string-comparison operators. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
9
10
<title>String Comparison</title>
</head>
11
12
13
<body>
<?php
// create array fruits
14
15
16
$fruits = array( "apple", "orange", "banana" );
17
18
for ( $i = 0; $i < count( $fruits ); $i++ )
{
// iterate through each array element
19
20
21
// call function strcmp to compare the array element
// to string "banana"
if ( strcmp( $fruits[ $i ], "banana" ) < 0 )
22
23
24
print( $fruits[ $i ] . " is less than banana " );
elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 )
print( $fruits[ $i ] . " is greater than banana " );
25
26
else
print( $fruits[ $i ] . " is equal to banana " );
27
28
29
// use relational operators to compare each element
// to string "apple"
33
Outline
compare.php
(1 of 2)
Checks whether the ith
element of the fruits
array preceeds the string
banana
 2008 Pearson Education,
Inc. All rights reserved.
if ( $fruits[ $i ] < "apple" )
30
print( "and less than apple! <br />" );
31
elseif ( $fruits[ $i ] > "apple" )
32
elseif ( $fruits[ $i ] == "apple" )
34
print( "and equal to apple! <br />" );
35
compare.php
} // end for
36
38
Outline
print( "and greater than apple! <br />" );
33
37
34
?><!-- end PHP script -->
(2 of 2)
</body>
39 </html>
Uses relational operators
to compare the element
of the fruits array
with the string apple
 2008 Pearson Education,
Inc. All rights reserved.
35
23.3 String Processing and Regular
Expressions (Cont.)
• Functions ereg and preg_match use regular expressions to search a string
for a specified pattern.
• If a pattern is found using ereg, it returns the length of the matched string—
which evaluates to true in a boolean context.
• Anything enclosed in single quotes in a print statement is not interpolated
(unless the single quotes are nested in a double-quoted string literal).
• Function ereg receives a regular expression pattern to search for and the
string to search.
• Function eregi performs case-insensitive pattern matches.
• Regular expressions can include metacharacters that specify patterns. For
example, the caret (^) metacharacter matches the beginning of a string, while
the dollar sign ($) matches the end of a string. The period (.) metacharacter
matches any single character.
• Bracket expressions are lists of characters enclosed in square brackets ([])
that match any single character from the list. Ranges can be specified by
supplying the beginning and the end of the range separated by a dash (-).
 2008 Pearson Education, Inc. All rights reserved.
36
23.3 String Processing and Regular
Expressions (Cont.)
• The special bracket expressions [[:<:]] and [[:>:]] match the beginning and end
of a word, respectively.
• Quantifiers are used in regular expressions to denote how often a particular character
or set of characters can appear in a match.
• The optional third argument to function ereg is an array that stores matches to each
parenthetical statement of the regular expression. The first element stores the string
matched for the entire pattern, and the remaining elements are indexed from left to
right.
• To find multiple instances of a given pattern, we must make multiple calls to ereg, and
remove matched instances before calling the function again by using a function such as
ereg_replace.
• Character classes, or sets of specific characters, are enclosed by the delimiters [: and
:]. When this expression is placed in another set of brackets, it is a regular expression
matching all of the characters in the class.
• A bracketed expression containing two or more adjacent character classes in the class
delimiters represents those character sets combined.
• Function ereg_replace takes three arguments—the pattern to match, a string to
replace the matched string and the string to search. The modified string is returned.
 2008 Pearson Education, Inc. All rights reserved.
1
2
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3
4
5
<!-- Fig. 23.8: expression.php -->
6
7
8
<!-- Regular expressions. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
9
10
<title>Regular expressions</title>
</head>
11
12
13
<body>
<?php
$search = "Now is the time";
print( "Test string is: '$search'<br /><br />" );
14
15
16
// call ereg to search for pattern 'Now' in variable search
17
18
if ( ereg( "Now", $search ) )
print( "String 'Now' was found.<br />" );
19
20
21
// search for pattern 'Now' in the beginning of the string
if ( ereg( "^Now", $search ) )
22
23
24
25
26
27
28
29
print( "String 'Now' found at beginning
of the line.<br />" );
// search for pattern 'Now' at the end of the string
if ( ereg( "Now$", $search ) )
print( "String 'Now' was found at the end
of the line.<br />" );
37
Outline
expression.php
(1 of 2)
String to search
Searches for the string
“Now” in $search
Checks if string “Now”
appears at the beginning
of $search
Checks if string “Now”
appears at the end of
$search
 2008 Pearson Education,
Inc. All rights reserved.
30
// search for any word ending in 'ow'
31
if ( ereg( "[[:<:]]([a-zA-Z]*ow)[[:>:]]", $search, $match ) )
print( "Word found ending in 'ow': " .
32
$match[ 1 ] . "<br />" );
33
34
35
// search for any words beginning with 't'
36
print( "Words beginning with 't' found: ");
38
Outline
Searches for a word
ending in “ow” and
stores matches in
$match array
expression.php
(2 of 2)
37
while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]",
38
$search, $match ) )
39
{
40
print( $match[ 1 ] . " " );
41
Prints first encountered
instance of word ending
in “ow”
42
43
// remove the first occurrence of a word beginning
44
// with 't' to find other instances in the string
45
$search = ereg_replace( $match[ 1 ], "", $search );
} // end while
46
47
48
Performs a caseinsensitive search for
words beginning with the
letter “t”
?><!-- end PHP script -->
</body>
49 </html>
Replaces the found
instance from the
previous call to eregi
with an empty string so
that the next instance of
the pattern can be found
and stored in $match
 2008 Pearson Education,
Inc. All rights reserved.
39
Quantifier
Matches
{n}
Exactly n times.
{m,n}
Between m and n times, inclusive.
{n,}
+
n or more times.
*
Zero or more times (same as {0,}).
?
Zero or one time (same as {0,1}).
One or more times (same as {1,}).
Fig. 23.9 | Some PHP quantifiers.
 2008 Pearson Education, Inc. All rights reserved.
40
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
White space.
lower
Lowercase letters.
upper
Uppercase letters.
Fig. 23.10 | Some PHP character classes.
 2008 Pearson Education, Inc. All rights reserved.
41
23.4 Form Processing and Business
Logic
• Superglobal arrays are associative arrays predefined by
PHP that hold variables acquired from user input, the
environment or the web server and are accessible in any
variable scope.
• The arrays $_GET and $_POST retrieve information sent
to the server by HTTP get and post requests,
respectively.
• Using method = "post" appends form data to the
browser request that contains the protocol and the
requested resource’s URL. Scripts located on the web
server’s machine can access the form data sent as part of
the request.
 2008 Pearson Education, Inc. All rights reserved.
42
Variable name
Description
$_SERVER
Data about the currently running server.
$_ENV
Data about the client’s environment.
$_GET
Data sent to the server by a get request.
$_POST
Data sent to the server by a post request.
$_COOKIE
Data contained in cookies on the client’s computer.
$GLOBALS
Array containing all global variables.
Fig. 23.11 | Some useful superglobal arrays.
 2008 Pearson Education, Inc. All rights reserved.
1
<?xml version = "1.0" encoding = "utf-8"?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
43
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
<!-- Fig. 23.12: form.html -->
6
7
8
<!-- XHTML form for gathering user input. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
9
10
11
<title>Sample form to take user input in XHTML</title>
<style type = "text/css">
.prompt { color: blue;
12
font-family: sans-serif;
13
14
font-size: smaller }
15
16
</style>
</head>
<body>
Appends form data to the
browser request that
contains the protocol and
the URL of the requested
resource
17
<h1>Sample Registration Form</h1>
18
19
20
21
<p>Please fill in all fields and click Register.</p>
22
Outline
form.html
(1 of 4)
Form data is posted to
form.php to be processed
<!-- post form data to form.php -->
<form method = "post" action = "form.php">
<div>
23
<img src = "images/user.gif" alt = "User" /><br />
24
25
<span class = "prompt">
Please fill out the fields below.<br />
26
</span>
27
 2008 Pearson Education,
Inc. All rights reserved.
28
29
<!-- create four text boxes for user input -->
<img src = "images/fname.gif" alt = "First Name" />
30
<input type = "text" name = "fname" /><br />
31
32
<img src = "images/lname.gif" alt = "Last Name" />
33
34
35
<input type = "text" name = "lname" /><br />
36
37
<input type = "text" name = "email" /><br />
38
<img src = "images/phone.gif" alt = "Phone" />
39
40
<input type = "text" name = "phone" /><br />
41
<span style = "font-size: 10pt">
42
43
Must be in the form (555)555-5555</span>
<br /><br />
<img src = "images/email.gif" alt = "Email" />
44
Outline
form.html
(2 of 4)
Creates form fields
44
45
46
47
<img src = "images/downloads.gif"
alt = "Publications" /><br />
48
49
50
<span class = "prompt">
Which book would you like information about?
</span><br />
51
52
53
<!-- create drop-down list containing book names -->
<select name = "book">
Creates drop-down list
with book names
 2008 Pearson Education,
Inc. All rights reserved.
54
<option>Internet and WWW How to Program 4e</option>
55
56
57
<option>C++ How to Program 6e</option>
<option>Java How to Program 7e</option>
<option>Visual Basic 2005 How to Program 3e</option>
58
59
60
61
62
63
64
</select>
<br /><br />
<img src = "images/os.gif" alt = "Operating System" />
<br /><span class = "prompt">
Which operating system are you currently using?
<br /></span>
65
66
67
<!-- create five radio buttons -->
<input type = "radio" name = "os" value = "Windows XP"
68
69
70
checked = "checked" /> Windows XP
<input type = "radio" name = "os" value =
"Windows Vista" /> Windows Vista<br />
71
72
73
74
75
76
<input type = "radio" name = "os" value =
"Mac OS X" /> Mac OS X
<input type = "radio" name = "os" value = "Linux" /> Linux
<input type = "radio" name = "os" value = "Other" />
Other<br />
45
Outline
form.html
(3 of 4)
Creates radio buttons
with “Windows XP”
initially selected
 2008 Pearson Education,
Inc. All rights reserved.
77
<!-- create a submit button -->
78
<input type = "submit" value = "Register" />
</div>
79
80
81
46
Outline
</form>
</body>
82 </html>
form.html
(4 of 4)
 2008 Pearson Education,
Inc. All rights reserved.
47
Good Programming Practice 23.1
Use meaningful XHTML object names for
input fields. This makes PHP scripts that
retrieve form data easier to understand.
 2008 Pearson Education, Inc. All rights reserved.
48
23.4 Form Processing and Business
Logic (Cont.)
• Function extract creates a variable/value pair
corresponding to each key/value pair in the associative
array passed as an argument.
• Business logic, or business rules, ensures that only valid
information is stored in databases.
• We escape the normal meaning of a character in a string
by preceding it with the backslash character (\).
• Function die terminates script execution. The function’s
optional argument is a string, which is printed as the
script exits.
 2008 Pearson Education, Inc. All rights reserved.
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
<!-- Fig. 23.13: form.php -->
6
7
8
<!-- Process information sent from form.html. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
9
10
<title>Form Validation</title>
<style type = "text/css">
11
body
{ font-family: arial, sans-serif }
12
div
{ font-size: 10pt;
table
text-align: center }
{ border: 0 }
13
14
td
15
16
Outline
form.php
(1 of 5)
{ padding-top: 2px;
padding-bottom: 2px;
padding-left: 10px;
17
18
19
20
21
padding-right: 10px }
.error
{ color: red }
.distinct { color: blue }
.name
{ background-color: #ffffaa }
22
.email
{ background-color: #ffffbb }
23
.phone
{ background-color: #ffffcc }
24
25
49
.os
</style>
26
</head>
27
<body>
{ background-color: #ffffdd }
 2008 Pearson Education,
Inc. All rights reserved.
28
<?php
Creates a variable/value pair for each key/value pair
Outline
in $_POST
29
extract( $_POST );
30
31
// determine whether phone number is valid and print
32
// an error message if not
33
if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) )
34
35
36
{
print( "<p><span class = 'error'>
Invalid phone number</span><br />
37
A valid phone number must be in the form
38
<strong>(555)555-5555</strong><br />
39
<span class = 'distinct'>
40
41
Click the Back button, enter a valid phone
number and resubmit.<br /><br />
42
Thank You.</span></p>" );
45
46
47
48
(2 of 5)
Ensures that phone
number is in proper
format
}
?><!-- end PHP script -->
<p>Hi
<span class = "distinct">
<strong><?php print( "$fname" ); ?></strong>
49
</span>.
50
51
Thank you for completing the survey.<br />
You have been added to the
52
<span class = "distinct">
53
form.php
die( "</body></html>" ); // terminate script execution
43
44
50
Terminates execution and
closes the document
properly
<strong><?php print( "$book " ); ?></strong>
54
</span>
55
mailing list.
 2008 Pearson Education,
Inc. All rights reserved.
56
57
58
</p>
<p><strong>The following information has been saved
in our database:</strong></p>
59
60
61
<table>
<tr>
<td class = "name">Name </td>
64
65
66
67
Outline
form.php
<td class = "email">Email</td>
<td class = "phone">Phone</td>
62
63
51
(3 of 5)
<td class = "os">OS</td>
</tr>
<tr>
<?php
// print each form field’s value
print( "<td>$fname $lname</td>
<td>$email</td>
68
69
70
<td>$phone</td>
<td>$os</td>" );
?><!-- end PHP script -->
71
72
73
Prints the value entered
in the email field in
form.html
74
75
</tr>
</table>
76
77
78
<br /><br /><br />
<div>This is only a sample form.
You have not been added to a mailing list.</div>
79
</body>
80 </html>
 2008 Pearson Education,
Inc. All rights reserved.
52
Outline
form.php
(4 of 5)
 2008 Pearson Education,
Inc. All rights reserved.
53
Outline
form.php
(5 of 5)
 2008 Pearson Education,
Inc. All rights reserved.
54
Software Engineering Observation 23.1
Use business logic to ensure that invalid
information is not stored in databases. When
possible, validate important or sensitive form
data on the server, since JavaScript may be
disabled by the client. Some data, such as
passwords, must always be validated on the
server side.
 2008 Pearson Education, Inc. All rights reserved.
55
Error-Prevention Tip 23.3
Be sure to close any open XHTML tags when
calling function die. Not doing so can produce
invalid XHTML output that will not display
properly in the client browser. Function die has
an optional parameter that specifies a message to
output when exiting, so one technique for closing
tags is to close all open tags using die, as in
die("</body></html>").
 2008 Pearson Education, Inc. All rights reserved.
56
23.5 Connecting to a Database
• Function mysql_connect connects to the MySQL database. It takes
three arguments—the server’s hostname, a username and a
password, and returns a database handle—a representation of PHP’s
connection to the database, or false if the connection fails.
• Function mysql_select_db specifies the database to be queried,
and returns a bool indicating whether or not it was successful.
• To query the database, we call function mysql_query, specifying the
query string and the database to query. This returns a resource
containing the result of the query, or false if the query fails. It can also
execute SQL statements such as INSERT or DELETE that do not
return results.
• Function mysql_error returns any error strings from the database.
• mysql_close closes the connection to the database specified in its
argument.
 2008 Pearson Education, Inc. All rights reserved.
1
2
3
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
6
<!-- Fig. 23.14: data.html -->
<!-- Form to query a MySQL database. -->
7
8
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
9
10
11
12
13
14
15
</style>
</head>
19
20
<body>
<h2> Querying a MySQL database.</h2>
24
25
(1 of 2)
Posts data to
database.php
font-weight: bold }
16
17
18
21
22
23
Outline
data.html
<title>Sample Database Query</title>
<style type = "text/css">
body { background-color: #F0E68C }
h2
{ font-family: arial, sans-serif;
color: blue }
input { background-color: blue;
color: yellow;
57
<form method = "post" action = "database.php">
<div>
<p>Select a field to display:
<!-- add a select box containing options -->
<!-- for SELECT query -->
 2008 Pearson Education,
Inc. All rights reserved.
<select name = "select">
26
27
<option selected = "selected">*</option>
28
<option>ID</option>
29
<option>Title</option>
30
<option>Category</option>
31
<option>ISBN</option>
<input type = "submit" value = "Send Query" />
33
data.html
(2 of 2)
</div>
34
36
Outline
</select></p>
32
35
58
</form>
</body>
37 </html>
Creates drop-down menu specifying
which data to output to the screen, with
* (all data) as the default selection
 2008 Pearson Education,
Inc. All rights reserved.
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
4
<!-- Fig. 23.15: database.php -->
6
<!-- Querying a database and displaying the results. -->
7
8
9
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Search Results</title>
10
database.php
(1 of 3)
<style type = "text/css">
body
11
{ font-family: arial, sans-serif;
12
background-color: #F0E68C }
13
14
table { background-color: #ADD8E6 }
td
{ padding-top: 2px;
15
padding-bottom: 2px;
16
padding-left: 4px;
17
padding-right: 4px;
18
19
20
border-width: 1px;
border-style: inset }
</style>
21
</head>
22
<body>
23
24
Outline
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
5
59
<?php
extract( $_POST );
Builds a SELECT query
with the selection made
in data.html
25
26
// build SELECT query
27
$query = "SELECT " . $select . " FROM books";
28
 2008 Pearson Education,
Inc. All rights reserved.
29
// Connect to MySQL
30
if ( !( $database = mysql_connect( "localhost",
60
"iw3htp4", "iw3htp4" ) ) )
die( "Could not connect to database </body></html>" );
31
32
Outline
33
34
// open Products database
35
36
37
if ( !mysql_select_db( "products", $database ) )
die( "Could not open products database </body></html>" );
38
// query Products database
39
if ( !( $result = mysql_query( $query, $database ) ) )
40
{
41
42
43
print( "Could not execute query! <br />" );
die( mysql_error() . "</body></html>" );
} // end if
44
45
46
47
48
49
mysql_close( $database );
?><!-- end PHP script -->
<h3>Search Results</h3>
<table>
Returns any error strings
from the database
Closes the connection to
the database
50
// fetch each record in result set
51
52
for ( $counter = 0; $row = mysql_fetch_row( $result );
$counter++ )
53
{
// build table to display results
55
print( "<tr>" );
56
(2 of 3)
Connects to database
using server hostname
localhost and
username and password
“iw3htp4”
Specifies products as
the database to be
queried
Queries $database
with $query
<?php
54
database.php
Returns an array with the
values for each column
of the current row in
$result
 2008 Pearson Education,
Inc. All rights reserved.
foreach ( $row as $key => $value )
57
print( "<td>$value</td>" );
58
61
Outline
59
print( "</tr>" );
60
} // end for
61
?><!-- end PHP script -->
62
63
</table>
64
<br />Your search yielded <strong>
65
<?php print( "$counter" ) ?> results.<br /><br /></strong>
66
<h5>Please email comments to
67
<a href = "mailto:[email protected]">
68
Deitel and Associates, Inc.</a>
69
70
database.php
(3 of 3)
</h5>
</body>
71 </html>
 2008 Pearson Education,
Inc. All rights reserved.
62
23.6 Using Cookies
• A cookie is a text file that a website stores on a client’s computer to
maintain information about the client during and between browsing
sessions.
• A server can access only the cookies that it has placed on the client.
• 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 indicates the expiration date of the cookie. A
cookie without a third argument is known as a session cookie, while
one with an expiration date is a persistent cookie. If only the name
argument is passed to function setcookie, the cookie is deleted
from the client’s computer.
• Cookies defined in function setcookie are sent to the client at the
same time as the information in the HTTP header; therefore, it needs
to be called before any XHTML is printed.
• The current time is returned by function time.
 2008 Pearson Education, Inc. All rights reserved.
1
<?xml version = "1.0" encoding = "utf-8"?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
4
63
5
<!-- Fig. 23.16: cookies.html -->
6
<!-- Gathering data to be written as a cookie. -->
7
8
9
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Writing a cookie to the client computer</title>
10
11
body
background-color: #99CCFF }
form
{ font-size: 10pt }
.submit { background-color: #F0E86C;
color: navy;
16
font-weight: bold }
18
19
20
21
22
23
24
(1 of 2)
{ font-family: arial, sans-serif;
15
17
cookies.html
<style type = "text/css">
12
13
14
Outline
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Posts form data to
cookies.php
</style>
</head>
<body>
<h2>Click Write Cookie to save your cookie data.</h2>
<form method = "post" action = "cookies.php">
<div>
<strong>Name:</strong><br />
<input type = "text" name = "Name" /><br />
Creates fields to gather
information to be written
into a cookie
25
26
<strong>Height:</strong><br />
27
<input type = "text" name = "Height" /><br />
28
 2008 Pearson Education,
Inc. All rights reserved.
29
<strong>Favorite Color:</strong><br />
30
<input type = "text" name = "Color" /><br />
64
Outline
31
<input type = "submit" value = "Write Cookie"
32
class = "submit" />
33
</div>
34
35
36
Form field
cookies.html
</form>
</body>
(2 of 2)
37 </html>
 2008 Pearson Education,
Inc. All rights reserved.
1
2
<?php
// Fig. 23.17: cookies.php
3
4
5
// Writing a cookie to the client.
extract( $_POST );
6
7
8
// write each form field’s value to a cookie and set the
// cookie’s expiration date
setcookie( "Name", $Name, time() + 60 * 60 * 24 * 5 );
9
10
setcookie( "Height", $Height, time() + 60 * 60 * 24 * 5 );
setcookie( "Color", $Color, time() + 60 * 60 * 24 * 5 );
11 ?><!-- end PHP script -->
12
13 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
14 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
15
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
16
65
Outline
cookies.php
(1 of 2)
Creates a cookie for each
entered value and sets the
expiration date to be five
days after the current
time
17 <html xmlns = "http://www.w3.org/1999/xhtml">
18
<head>
19
20
21
<title>Cookie Saved</title>
<style type = "text/css">
body { font-family: arial, sans-serif }
22
23
24
span { color: blue }
</style>
</head>
25
26
<body>
<p>The cookie has been set with the following data:</p>
27
28
29
<!-- print each form field’s value -->
<br /><span>Name:</span><?php print( $Name ) ?><br />
 2008 Pearson Education,
Inc. All rights reserved.
30
<span>Height:</span><?php print( $Height ) ?><br />
31
<span>Favorite Color:</span>
32
<span style = "color: <?php print( "$Color\">$Color" ) ?>
33
</span><br />
34
<p>Click <a href = "readCookies.php">here</a>
to read the saved cookie.</p>
35
36
</body>
37 </html>
Links to the page that
displays the contents of
the cookie
66
Outline
cookies.php
(2 of 2)
 2008 Pearson Education,
Inc. All rights reserved.
67
Software Engineering Observation 23.2
Some clients do not accept cookies. When
a client declines a cookie, the browser
application normally informs the user that
the site may not function correctly without
cookies enabled.
 2008 Pearson Education, Inc. All rights reserved.
68
Software Engineering Observation 23.3
Cookies should not be used to store
e-mail addresses or private data on a
client’s computer.
 2008 Pearson Education, Inc. All rights reserved.
69
23.6 Using Cookies (Cont.)
• When using Internet Explorer, cookies are stored
in a Cookies directory on the client’s machine.
In Firefox, cookies are stored in a file named
cookies.txt.
 2008 Pearson Education, Inc. All rights reserved.
70
Fig. 23.18 | IE7’s Cookies directory before a cookie is written.
 2008 Pearson Education, Inc. All rights reserved.
71
Fig. 23.19 | IE7’s Cookies directory after a cookie is written.
 2008 Pearson Education, Inc. All rights reserved.
72
23.6 Using Cookies (Cont.)
• PHP creates the superglobal array $_COOKIE,
which contains all the cookie values indexed by
their names.
 2008 Pearson Education, Inc. All rights reserved.
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
<!-- Fig. 23.20: readCookies.php -->
6
7
8
<!-- Displaying the cookie’s contents. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
9
10
<title>Read Cookies</title>
<style type = "text/css">
11
body
{ font-family: arial, sans-serif }
12
table
{ border-width: 5px;
13
14
td
border-style: outset }
{ padding: 10px }
15
16
.key
{ background-color: #F0E68C }
.value { background-color: #FFA500 }
17
18
19
20
21
73
Outline
readCookies.php
(1 of 2)
</style>
</head>
<body>
<p>
<strong>The following data is saved in a cookie on your
computer.</strong>
22
23
</p>
24
25
<table>
<?php
26
// iterate through array $_COOKIE and print
27
// name and value of each cookie
 2008 Pearson Education,
Inc. All rights reserved.
foreach ( $_COOKIE as $key => $value )
28
<td class = 'value' >$value</td></tr>" );
30
?><!-- end PHP script -->
31
33
Outline
print( "<tr><td class = 'key' >$key</td>
29
32
74
</table>
</body>
Iterates through
all values in
$_COOKIE
readCookies.php
34 </html>
(2 of 2)
 2008 Pearson Education,
Inc. All rights reserved.
75
23.7 Dynamic Content
• Function isset allows you to find out if a
variable has a value.
• A variable variable ($$variable) allows the
code to reference variables dynamically. You can
use this expression to obtain the value of the
variable whose name is equal to the value of
$variable.
• The quotemeta function inserts a backslash (\)
before any special characters in the passed string.
 2008 Pearson Education, Inc. All rights reserved.
1
2
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3
4
5
<!-- Fig. 23.21: dynamicForm.php -->
6
7
8
<!-- Dynamic form. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
9
10
11
12
13
<title>Sample form to take user input in XHTML</title>
<style type = "text/css">
td
Outline
dynamicForm.php
(1 of 12)
{ padding-top: 2px;
padding-bottom: 2px;
padding-left: 10px;
14
15
16
div
div div
padding-right: 10px }
{ text-align: center }
{ font-size: larger }
17
18
.name
.email
{ background-color: #ffffaa }
{ background-color: #ffffbb }
19
20
21
.phone
.os
.smalltext
{ background-color: #ffffcc }
{ background-color: #ffffdd }
{ font-size: smaller }
22
23
24
.prompt
{ color: blue;
font-family: sans-serif;
font-size: smaller }
25
26
.largeerror { color: red }
.error
{ color: red;
27
28
29
76
font-size: smaller }
</style>
</head>
 2008 Pearson Education,
Inc. All rights reserved.
30
31
32
33
<body>
77
<?php
Outline
extract( $_POST );
$iserror = false;
34
35
// array of book titles
36
37
38
$booklist = array( "Internet and WWW How to Program 4e",
"C++ How to Program 6e", "Java How to Program 7e",
"Visual Basic 2005 How to Program 3e" );
dynamicForm.php
(2 of 12)
39
40
// array of possible operating systems
41
$systemlist = array( "Windows XP", "Windows Vista",
"Mac OS X", "Linux", "Other");
42
43
44
// array of name values for the text input fields
45
$inputlist = array( "fname" => "First Name",
46
"lname" => "Last Name", "email" => "Email",
47
48
49
"phone" => "Phone" );
// ensure that all fields have been filled in correctly
50
if ( isset ( $submit ) )
51
{
52
53
Checks whether the Register
button has been pressed
if ( $fname == "" )
{
54
$formerrors[ "fnameerror" ] = true;
55
$iserror = true;
56
57
Checks that the first name field is
not blank
} // end if
Makes an entry in the error array
Sets $iserror to true
 2008 Pearson Education,
Inc. All rights reserved.
58
59
60
if ( $lname == "" )
{
$formerrors[ "lnameerror" ] = true;
61
62
63
$iserror = true;
} // end if
64
65
if ( $email == "" )
{
66
67
68
69
$formerrors[ "emailerror" ] = true;
$iserror = true;
} // end if
70
71
72
if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) )
{
$formerrors[ "phoneerror" ] = true;
73
74
75
$iserror = true;
} // end if
76
77
if ( !$iserror )
{
78
79
80
81
82
78
Outline
Checks that all
other form fields
are filled in
correctly
dynamicForm.php
(3 of 12)
// build INSERT query
$query = "INSERT INTO contacts " .
"( LastName, FirstName, Email, Phone, Book, OS ) " .
"VALUES ( '$lname', '$fname', '$email', " .
"'" . quotemeta( $phone ) . "', '$book', '$os' )";
Inserts a backslash
before the parentheses
in the phone number
 2008 Pearson Education,
Inc. All rights reserved.
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
79
// Connect to MySQL
if ( !( $database = mysql_connect( "localhost",
"iw3htp4", "iw3htp4" ) ) )
die( "Could not connect to database" );
// open MailingList database
if ( !mysql_select_db( "MailingList", $database ) )
die( "Could not open MailingList database" );
Outline
dynamicForm.php
(4 of 12)
// execute query in MailingList database
if ( !( $result = mysql_query( $query, $database ) ) )
{
print( "Could not execute query! <br />" );
die( mysql_error() );
} // end if
mysql_close( $database );
print( "<p>Hi<span class = 'prompt'>
<strong>$fname</strong></span>.
Thank you for completing the survey.<br />
You have been added to the
<span class = 'prompt'>
<strong>$book</strong></span>
mailing list.</p>
<strong>The following information has been saved
in our database:</strong><br />
 2008 Pearson Education,
Inc. All rights reserved.
113
<table><tr>
114
<td class = 'name'>Name </td>
115
116
<td class = 'email'>Email</td>
<td class = 'phone'>Phone</td>
117
<td class = 'os'>OS</td>
118
</tr><tr>
119
120
121
<!-- print each form field’s value -->
<td>$fname $lname</td>
122
<td>$email</td>
123
<td>$phone</td>
124
<td>$os</td>
125
126
</tr></table>
127
<br /><br /><br />
128
<div><div>
129
<a href = 'formDatabase.php'>
130
131
132
Click here to view entire database.</a>
</div>This is only a sample form.
You have not been added to a mailing list.
133
</div></body></html>" );
134
135
136
die();
} // end if
} // end if
137
138
139
print( "<h1>Sample Registration Form.</h1>
Please fill in all fields and click Register." );
80
Outline
dynamicForm.php
(5 of 12)
Ends script here if
there were no errors
in the user input
Section to be
executed only if
$iserror is true
140
 2008 Pearson Education,
Inc. All rights reserved.
141
142
if ( $iserror )
{
143
144
145
print( "<br /><span class = 'largeerror'>
Fields with * need to be filled in properly.</span>" );
} // end if
146
147
148
print( "<!-- post form data to form.php -->
<form method = 'post' action = 'dynamicForm.php'>
81
149
150
<img src = 'images/user.gif' alt = 'User' /><br />
<span class = 'prompt'>
151
152
153
Please fill out the fields below.<br /> </span>
154
155
156
157
158
159
160
161
162
163
164
Outline
dynamicForm.php
(6 of 12)
Alerts the user that
there are errors
<!-- create four text boxes for user input -->" );
foreach ( $inputlist as $inputname => $inputalt )
{
$inputtext = $inputvalues[ $inputname ];
print( "<img src = 'images/$inputname.gif'
alt = '$inputalt' /><input type = 'text'
name = '$inputname' value = '" . $$inputname . "' />" );
if ( $formerrors[ ( $inputname )."error" ] == true )
print( "<span class = 'error'>*</span>" );
165
166
print( "<br />" );
} // end foreach
167
168
169
if ( $formerrors[ "phoneerror" ] )
print( "<span class = 'error'>" );
Iterates through
$inputlist to create
the form’s text boxes
Outputs the field’s
image
Sets the name attribute
of the text field to
$inputname
Sets the value attribute of the text
field to the value of the variable
Puts an asterisk with the name of $inputname’s
next to fields that
value
have errors
 2008 Pearson Education,
Inc. All rights reserved.
170
171
else
print("<span class = 'smalltext'>");
172
173
174
<img src = 'images/downloads.gif'
alt = 'Publications' /><br />
178
179
<span class = 'prompt'>
180
Which book would you like information about?
181
182
</span><br />
183
<!-- create drop-down list containing book names -->
184
185
<select name = 'book'>" );
186
foreach ( $booklist as $currbook )
187
188
189
{
193
194
195
Outline
print( "Must be in the form (555)555-5555
</span><br /><br />
175
176
177
190
191
192
82
dynamicForm.php
(7 of 12)
print( "<option" );
if ( ( $currbook == $book ) )
print( " selected = 'true'" );
print( ">$currbook</option>" );
} // end foreach
Creates drop-down
list for books,
keeping the
previously selected
one selected
 2008 Pearson Education,
Inc. All rights reserved.
196
print( "</select><br /><br />
197
<img src = 'images/os.gif' alt = 'Operating System' />
198
<br /><span class = 'prompt'>
199
200
Which operating system are you currently using?
<br /></span>
201
202
203
<!-- create five radio buttons -->" );
204
205
$counter = 0;
206
foreach ( $systemlist as $currsystem )
207
{
208
209
print( "<input type = 'radio' name = 'os'
value = '$currsystem'" );
210
211
if ( $currsystem == $os )
212
213
214
215
216
Outline
dynamicForm.php
(8 of 12)
print( "checked = 'checked'" );
elseif ( !$os && $counter == 0 )
print( "checked = 'checked'" );
print( " />$currsystem" );
217
218
// put a line break in list of operating systems
219
220
if ( $counter == 1 ) print( "<br />" );
++$counter;
221
83
} // end foreach
Creates radio
buttons for
operating-system
selection, keeping
the previously
selected option
selected
222
 2008 Pearson Education,
Inc. All rights reserved.
223
print( "<!-- create a submit button -->
224
<br /><input type = 'submit' name = 'submit'
225
value = 'Register' /></form></body></html>" );
226
84
Outline
?><!-- end PHP script -->
dynamicForm.php
(9 of 12)
 2008 Pearson Education,
Inc. All rights reserved.
85
Outline
dynamicForm.php
(10 of 12)
 2008 Pearson Education,
Inc. All rights reserved.
86
Outline
dynamicForm.php
(11 of 12)
 2008 Pearson Education,
Inc. All rights reserved.
87
Outline
dynamicForm.php
(12 of 12)
 2008 Pearson Education,
Inc. All rights reserved.
1
2
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3
4
5
<!-- Fig. 23.22: formDatabase.php -->
6
7
8
<!-- Displaying the MailingList database. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
9
10
body
14
15
16
table { background-color: #ADD8E6 }
td
{ padding-top: 2px;
padding-bottom: 2px;
17
18
padding-left: 4px;
padding-right: 4px;
19
20
21
border-width: 1px;
border-style: inset }
22
23
24
h3
Outline
formDatabase.php
(1 of 3)
<title>Search Results</title>
<style type = "text/css">
11
12
13
88
{ font-family: arial, sans-serif;
background-color: #F0E68C }
{ color: blue }
</style>
</head>
<body>
<?php
25
26
extract( $_POST );
27
28
29
// build SELECT query
$query = "SELECT * FROM contacts";
Selects all fields from
the contacts
database to display
 2008 Pearson Education,
Inc. All rights reserved.
30
31
32
33
34
// Connect to MySQL
if ( !( $database = mysql_connect( "localhost",
"iw3htp4", "iw3htp4" ) ) )
die( "Could not connect to database </body></html>" );
35
36
37
// open MailingList database
if ( !mysql_select_db( "MailingList", $database ) )
die( "Could not open MailingList database </body></html>" );
38
39
// query MailingList database
40
41
42
if ( !( $result = mysql_query( $query, $database ) ) )
{
print( "Could not execute query! <br />" );
43
44
45
die( mysql_error() . "</body></html>" );
} // end if
?><!-- end PHP script -->
46
47
<h3>Mailing List Contacts</h3>
48
49
50
<table>
<tr>
<td>ID</td>
51
52
53
<td>Last Name</td>
<td>First Name</td>
<td>E-mail Address</td>
54
55
<td>Phone Number</td>
<td>Book</td>
56
57
58
89
Outline
formDatabase.php
(2 of 3)
<td>Operating System</td>
</tr>
<?php
 2008 Pearson Education,
Inc. All rights reserved.
59
// fetch each record in result set
60
for ( $counter = 0; $row = mysql_fetch_row( $result );
$counter++ )
61
90
Outline
{
62
63
// build table to display results
64
print( "<tr>" );
formDatabase.php
foreach ( $row as $key => $value )
(3 of 3)
65
66
print( "<td>$value</td>" );
67
68
print( "</tr>" );
69
} // end for
70
71
mysql_close( $database );
72
?><!-- end PHP script -->
73
74
75
</table>
</body>
76 </html>
 2008 Pearson Education,
Inc. All rights reserved.
91
23.8 Operator Precedence Chart
• The following table contains a list of PHP
operators in decreasing order of precedence.
 2008 Pearson Education, Inc. All rights reserved.
92
Operator
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
Fig. 23.23 | PHP operator precedence and associativity. (Part 1 of 3.)
 2008 Pearson Education, Inc. All rights reserved.
93
Operator
Type
Associativity
<<
bitwise shift left
left to right
>>
bitwise shift right
<
>
<=
>=
less than
greater than
less than or equal
greater than or equal
none
==
!=
===
!==
equal
not equal
identical
not identical
none
&
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
Fig. 23.23 | PHP operator precedence and associativity. (Part 2 of 3.)
 2008 Pearson Education, Inc. All rights reserved.
94
Operator
Type
Associativity
=
+=
-=
*=
/=
&=
|=
^=
.=
<<=
>>=
assignment
left to right
addition assignment
subtraction assignment
multiplication assignment
division assignment
bitwise AND assignment
bitwise OR assignment
bitwise exclusive OR assignment
concatenation assignment
bitwise shift left assignment
bitwise shift right assignment
and
logical AND
left to right
xor
exclusive OR
left to right
or
logical OR
left to right
,
list
left to right
Fig. 23.23 | PHP operator precedence and associativity. (Part 3 of 3.)
 2008 Pearson Education, Inc. All rights reserved.