23_PHP_part_1-2-3

Download Report

Transcript 23_PHP_part_1-2-3

1
Credits: Parts of the slides are based on slides created by textbook authors,
P.J. Deitel and H. M. Deitel by Prentice Hall
Jozef Goetz contribution, 2011
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
Jozef Goetz contribution, 2011
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
Jozef Goetz contribution, 2011
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.
Jozef Goetz contribution, 2011
4
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
Jozef Goetz contribution, 2011
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.
Jozef Goetz contribution, 2011
6
PHP was rated the best scripting language
7
 The survey asked more than 500 developers to rate the scripting languages
they use according to features and capabilities such as
(http://www.infoq.com/news/2009/03/top-scripting-languages-php-ruby) :











ease of use,
exception handling,
extensibility,
maintainability/readability,
cross-platform portability,
community,
availability of tools,
quality of tools,
performance,
memory management,
client-side scripting, and security.
 Languages in the survey included: Actionscript, Flex, Java Script, F#, Windows
Powershell, Perl, PHP, Python, Ruby, and VB Script
 The study concluded that PHP was the best all-around scripting language for
web applications with a large community and lots of readily available tools.
Jozef Goetz contribution, 2011
PHP most popular scripting language
8
 From PHP for theWeb ed 4 by Larry Ullman (2011) p Xiii:
 PHP is most popular tool available for developing dynamic
Web sites
 PHP is in use on over 75% of all Web sites (Jan 2011) and
it is the fourth most popular programming language overall
 PHP can do certain task faster and more easily than the
alternatives
 open source nature means that PHP’s users are driving its
development , not some corporate entity
 PHP is used by:
 the biggest web sites Yahoo!, Wikipedia, Facebook,
 content management tools: WordPress, Drupal, Moodle, and Joomla
 By learning you’ll provide yourself with either a usable hobby or a
Jozef Goetz contribution, 2011
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.
Jozef Goetz contribution, 2011
9
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.
Jozef Goetz contribution, 2011
10
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
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
12
<head>
<title>Using PHP document</title>
13
</head>
14
<body style = "font-size: 2em">
15
first.php
$name = "Harvey"; // declaration and initialization
10 ?><!-- end PHP script -->
11
Delimiters enclosing
PHP script
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>
22 </html>
Jozef Goetz contribution, 2011
Interpolates the variable so
that its value will be output to
the XHTML document
11
Common Programming Error 23.1
 Failing to precede a variable name
with a $ is a syntax error.
Jozef Goetz contribution, 2011
12
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.
Jozef Goetz contribution, 2011
13
Common Programming Error 23.3
 Forgetting to terminate a statement
with a semicolon (;) is a syntax error.
Jozef Goetz contribution, 2011
14
15
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.
Jozef Goetz contribution, 2011
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.
Jozef Goetz contribution, 2011
16
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
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
print( "$testString is a(n) " . gettype( $testString )
. "<br />" );
Jozef Goetz contribution, 2011
Outputs the type of
$testString
17
23
print( "$testDouble is a(n) " . gettype( $testDouble )
. "<br />" );
24
25
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
35
settype( $testString, "double" );
print( " as a double is $testString <br />" );
36
print( "$testString" );
37
38
settype( $testString, "integer" );
print( " as an integer is $testString <br />" );
39
settype( $testString, "string" );
40
print( "converting back to a string results in
41
Outline
print( "$testInteger is a(n) " . gettype( $testInteger)
$testString <br /><br />" );
42
Jozef Goetz contribution, 2011
Modifies $testString to be a
double
Modifies $testString to be an
integer
Modifies $testString to be a
string
18
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 );
53
(3 of 3)
gettype( $data ) );
51
?><!-- end PHP script -->
</body>
54 </html>
Jozef Goetz contribution, 2011
Outline
data.php
print( "<br /><br />after casting, $data is a " .
50
52
Temporarily casts $data as
a double and an integer
Concatenation
19
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.
Jozef Goetz contribution, 2011
20
23.2 PHP Basics (Cont.)
 Function define creates a named constant.
 It takes two arguments—the name and value of the
constant. Line 17 of Fig.23.4
 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.
Jozef Goetz contribution, 2011
21
Common Programming Error 23.4
 Assigning a value to a constant after
it is declared is a syntax error.
Jozef Goetz contribution, 2011
22
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?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">
<!-- Fig. 23.4: operators.php -->
<!-- Using arithmetic operators. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Using arithmetic operators</title>
</head>
<body>
<?php
$a = 5;
print( "The value of variable a is $a <br />" );
operators.php
(1 of 3)
Creates the named constant
VALUE with a value of 5
// define constant VALUE
define( "VALUE", 5 );
Equivalent to $a = $a * 2
// add constant VALUE to variable $a
$a = $a + VALUE;
print( "Variable a after adding constant VALUE
is $a <br />" );
// multiply variable $a by 2
$a *= 2;
print( "Multiplying variable a by 2 yields $a <br />" );
Jozef Goetz contribution, 2011
Outline
23
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// test if variable $a is less than 50
if ( $a < 50 )
print( "Variable a is less than 50 <br />" );
// add 40 to variable $a
$a += 40;
print( "Variable a after adding 40 is $a <br />" );
Uses a comparison operator with a
// test if variable $a is 50 or less
variable and an integer
if ( $a < 51 )
print( "Variable a is still 50 or less<br />" );
// test if variable $a is between 50 and 100, inclusive
elseif ( $a < 101 )
print( "Variable a is now between 50 and 100,
inclusive<br />" );
else
print( "Variable a is now greater than 100 <br />" );
// print an uninitialized variable
print( "Using a variable before initializing:
$nothing <br />" ); // nothing evaluates to ""
// add constant VALUE to an uninitialized variable
$test = $num + VALUE; // num evaluates to 0
Uninitialized variable $num
evaluates to 0
Jozef Goetz contribution, 2011
Outline
operators.php
(2 of 3)
24
print( "An uninitialized variable plus constant
53
Outline
VALUE yields $test <br />" );
54
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 -->
</body>
62 </html>
Jozef Goetz contribution, 2011
operators.php
(3 of 3)
25
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.
Jozef Goetz contribution, 2011
26
27
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.
Jozef Goetz contribution, 2011
23.2 PHP Basics (Cont.)
28
 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.
Jozef Goetz contribution, 2011
23.2 PHP Basics (Cont.)
29
 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.)
foreach ( $fourth as $element => $value )
print( "$element is the $value month <br />" );
Jozef Goetz contribution, 2011
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
3
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Outline
4
5
6
<!-- Fig. 23.6: arrays.php -->
<!-- Array manipulation. -->
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
<head>
9
<title>Array manipulation</title>
10
</head>
11
12
13
arrays.php
(1 of 4)
Automatically creates array
$first
<body>
<?php
// create array first
Sets the first element of array $first to
the string “zero”
14
15
16
print( "<strong>Creating the first array</strong><br />" );
$first[ 0 ] = "zero";
“three” is appended to the
$first[ 1 ] = "one";
17
18
19
20
$first[ 2 ] = "two";
$first[] = "three";
21
22
for ( $i = 0; $i < count( $first ); $i++ )
print( "Element $i is $first[$i] <br />" );
// print each element’s index and value
23
Returns the number of
elements in the array
Jozef Goetz contribution, 2011
end of array $first
30
24
25
print( "<br /><strong>Creating the second array
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
Jozef Goetz contribution, 2011
Returns the index of the
element being pointed
to;
Moves the internal
pointer to the next
element and returns it;
When function cannot
return an index =>
$element = false
returns false when there
are no more elements in
the array
31
print( "<br /><strong>Creating the fourth array
46
Outline
</strong><br />" );
47
48
49
// call function array to create array fourth using
50
// string indices
51
$fourth = array(
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 )
print( "$element is the $value month <br />" );
62
63
64
?><!-- end PHP script -->
</body>
65 </html>
Iterates through each
element in array
$fourth
Jozef Goetz contribution, 2011
Stores the
index of the
element
Stores the value of the
element
Uses operator => to
initialize the element with
index “January” to have
value “first”
32
Outline
arrays.php
(4 of 4)
Jozef Goetz contribution, 2011
33
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.
Jozef Goetz contribution, 2011
34
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
3
4
5
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
6
<!-- Using the string-comparison operators. -->
7
8
9
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>String Comparison</title>
10
11
12
<!-- Fig. 23.7: compare.php -->
compare.php
(1 of 2)
</head>
<body>
<?php
13
14
15
16
// create array fruits
$fruits = array( "apple", "orange", "banana" );
17
for ( $i = 0; $i < count( $fruits ); $i++ )
18
19
20
{
// iterate through each array element
// call function strcmp to compare the array element
// to string "banana"
21
22
if ( strcmp( $fruits[ $i ], "banana" ) < 0 )
print( $fruits[ $i ] . " is less than banana " );
23
elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 )
24
Outline
print( $fruits[ $i ] . " is greater than banana " );
25
26
27
else
print( $fruits[ $i ] . " is equal to banana " );
28
// use relational operators to compare each element
29
// to string "apple"
Jozef Goetz contribution, 2011
Checks whether the ith element
of the fruits array preceeds
the string banana
35
if ( $fruits[ $i ] < "apple" )
30
print( "and less than apple! <br />" );
31
print( "and greater than apple! <br />" );
33
elseif ( $fruits[ $i ] == "apple" )
34
print( "and equal to apple! <br />" );
35
38
compare.php
} // end for
36
37
Outline
elseif ( $fruits[ $i ] > "apple" )
32
?><!-- end PHP script -->
(2 of 2)
</body>
39 </html>
Jozef Goetz contribution, 2011
Uses relational operators to
compare the element of the
fruits array with the string
apple
36
23.3 String Processing and Regular
Expressions (Cont.)
37
 Goal: find pattern in text
 Regular expression (as ereg ) – specially formated strings used to find patterns in
text
 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 first stringwhich evaluates to true in a boolean context.
 Function ereg receives a regular expression pattern to search for and the string to
search.
 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.
 Function eregi performs case-insensitive pattern matches.
 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.
Jozef Goetz contribution, 2011
23.3 String Processing and Regular
Expressions (Cont.)
38
 Anything enclosed in single quotes in a print statement is not interpolated
(unless the single quotes are nested in a double-quoted string literal).
 Regular expressions can include metacharacters that specify patterns.
 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 (-).
ex: [a-zA-Z]
 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.
Jozef Goetz contribution, 2011
23.3 String Processing and Regular
Expressions (Cont.)
39
 A character class represents a group of characters that might appear
in a string ex. [[:alpha:]]
 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 3 arguments—
the pattern to match,
a string to replace the matched string and
the string to search.
 The modified string is returned.
Jozef Goetz contribution, 2011
40
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.
Jozef Goetz contribution, 2011
41
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.
Jozef Goetz contribution, 2011
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
3
4
5
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
6
<!-- Regular expressions. -->
7
8
9
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Regular expressions</title>
10
11
12
<!-- Fig. 23.8: expression.php -->
</head>
<body>
<?php
String to search
13
14
15
16
$search = "Now is the time";
print( "Test string is: '$search'<br /><br />" );
17
if ( ereg( "Now", $search ) )
print( "String 'Now' was found.<br />" );
// search for pattern 'Now' in the beginning of the string
21
22
if ( ereg( "^Now", $search ) )
print( "String 'Now' found at beginning
of the line.<br />" );
24
25
26
27
28
Searches for the string “Now”
in $search
// call ereg to search for pattern 'Now' in variable search
18
19
20
23
Outline
Checks if string “Now” appears
at the beginning of $search
Checks if string “Now” appears
at the end of $search
// 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 />" );
29
expression.php
Jozef Goetz contribution, 2011
(1 of 2)
42
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: ");
37
38
40
41
Searches for a word ending in
“ow” and stores matches in
$match array
Quantifier * matches the
preceding pattern 0 or more
times
while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]",
$search, $match ) )
39
{
print( $match[ 1 ] . " " );
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 );
46
} // end while
Function ereg_replace takes 3 arguments
?><!-- end PHP script -->•the pattern to match,
•a string to replace the matched string and
48
</body>
•the string to search.
The modified string is returned.
49 </html>
47
Outline
expression.php
(2 of 2)
$match[0] stores the string
matches for the entire pattern
Prints first $match[1]
encountered instance of word
ending in “ow”;
Second encountered instance of
word ending in “ow” will be in
$match[2]
Performs a case-insensitive
search for words beginning with
the letter “t” and then
[[:alpha:]]+ i.e. [a-zA-Z]).
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
Jozef Goetz contribution, 2011
43
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.
Jozef Goetz contribution, 2011
44
45
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.
Jozef Goetz contribution, 2011
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?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">
<!-- Fig. 23.12: form.html -->
<!-- XHTML form for gathering user input. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Sample form to take user input in XHTML</title>
<style type = "text/css">
Appends form data to the
.prompt { color: blue;
browser request that contains
font-family: sans-serif;
the protocol and the URL of the
font-size: smaller }
requested resource
</style>
</head>
<body>
<h1>Sample Registration Form</h1>
<p>Please fill in all fields and click Register.</p>
<!-- post form data to form.php -->
<form method = "post" action = "form.php">
<div>
<img src = "images/user.gif" alt = "User" /><br />
<span class = "prompt">
Please fill out the fields below.<br />
</span>
Form data is posted to form.php
to be processed
Jozef Goetz contribution, 2011
Outline
form.html
(1 of 4)
46
28
29
30
<!-- create four text boxes for user input -->
<img src = "images/fname.gif" alt = "First Name" />
<input type = "text" name = "fname" /><br />
Outline
31
32
33
<img src = "images/lname.gif" alt = "Last Name" />
<input type = "text" name = "lname" /><br />
34
35
<img src = "images/email.gif" alt = "Email" />
36
37
<input type = "text" name = "email" /><br />
38
39
<img src = "images/phone.gif" alt = "Phone" />
<input type = "text" name = "phone" /><br />
40
41
42
43
<span style = "font-size: 10pt">
Must be in the form (555)555-5555</span>
<br /><br />
44
45
46
47
48
49
50
51
52
53
<img src = "images/downloads.gif"
alt = "Publications" /><br />
<span class = "prompt">
Which book would you like information about?
</span><br />
<!-- create drop-down list containing book names -->
<select name = "book">
Creates drop-down list with
book names
Jozef Goetz contribution, 2011
form.html
(2 of 4)
Creates form fields
47
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
</select>
<br /><br />
61
62
63
64
<img src = "images/os.gif" alt = "Operating System" />
<br /><span class = "prompt">
Which operating system are you currently using?
<br /></span>
65
66
67
68
69
<!-- create five radio buttons -->
<input type = "radio" name = "os" value = "Windows XP"
checked = "checked" /> Windows XP
<input type = "radio" name = "os" value =
70
71
"Windows Vista" /> Windows Vista<br />
<input type = "radio" name = "os" value =
72
73
"Mac OS X" /> Mac OS X
<input type = "radio" name = "os" value = "Linux" /> Linux
74
<input type = "radio" name = "os" value = "Other" /> Other
75
76
<br />
Jozef Goetz contribution, 2011
Outline
form.html
(3 of 4)
Creates radio buttons with
“Windows XP” initially
selected
48
77
<!-- create a submit button -->
78
<input type = "submit" value = "Register" />
80
81
Outline
</div>
79
</form>
</body>
82 </html>
form.html
(4 of 4)
Jozef Goetz contribution, 2011
49
Good Programming Practice 23.1
 Use meaningful XHTML object names for
input fields.
 This makes PHP scripts that retrieve form
data easier to understand.
Jozef Goetz contribution, 2011
50
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.
Jozef Goetz contribution, 2011
51
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?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">
<!-- Fig. 23.13: form.php -->
<!-- Process information sent from form.html. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Form Validation</title>
<style type = "text/css">
body
{ font-family: arial, sans-serif }
div
{ font-size: 10pt;
text-align: center }
table
{ border: 0 }
td
{ padding-top: 2px;
padding-bottom: 2px;
padding-left: 10px;
padding-right: 10px }
.error
{ color: red }
.distinct { color: blue }
.name
{ background-color: #ffffaa }
.email
{ background-color: #ffffbb }
.phone
{ background-color: #ffffcc }
.os
{ background-color: #ffffdd }
</style>
</head>
<body>
Jozef Goetz contribution, 2011
Outline
form.php
(1 of 5)
52
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
extract( $_POST );
Creates a variable/value pair for each key/value pair in $_POST
// determine whether phone number is valid and print
Ensures that phone number is
in proper format
// an error message if not
if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) )
{
print( "<p><span class = 'error'>
Invalid phone number</span><br />
A valid phone number must be in the form
<strong>(555)555-5555</strong><br />
<span class = 'distinct'>
Click the Back button, enter a valid phone
number and resubmit.<br /><br />
Thank You.</span></p>" );
die( "</body></html>" ); // terminate script execution
}
?><!-- end PHP script -->
Terminates execution and closes
<p>Hi
the document properly
<span class = "distinct">
<strong><?php print( "$fname" ); ?></strong>
</span>.
Thank you for completing the survey.<br />
You have been added to the
<span class = "distinct">
<strong><?php print( "$book " ); ?></strong>
</span>
mailing list.
Jozef Goetz contribution, 2011
53
56
57
58
59
60
61
62
63
64
65
66
67
</p>
<p><strong>The following information has been saved
in our database:</strong></p>
<table>
<tr>
<td class = "name">Name </td>
<td class = "email">Email</td>
<td class = "phone">Phone</td>
<td class = "os">OS</td>
</tr>
<tr>
<?php
68
// print each form field’s value
69
print( "<td>$fname $lname</td>
70
<td>$email</td>
71
<td>$phone</td>
72
<td>$os</td>" );
73
?><!-- end PHP script -->
74
</tr>
Prints the value entered in the
email field in form.html
75
</table>
76
<br /><br /><br />
77
<div>This is only a sample form.
78
You have not been added to a mailing list.</div>
79
</body>
80 </html>
Jozef Goetz contribution, 2011
Outline
form.php
(3 of 5)
54
Outline
form.php
(4 of 5)
Jozef Goetz contribution, 2011
55
Outline
form.php
(5 of 5)
Jozef Goetz contribution, 2011
56
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.
Jozef Goetz contribution, 2011
57
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>").
Jozef Goetz contribution, 2011
58
23.5 Connecting to a Database
59
 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
Jozef
Goetz contribution, 2011 closes
the connection to the database specified in its argument.
1
<?xml version = "1.0" encoding = "utf-8"?>
2
3
<!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
16
17
18
19
<title>Sample Database Query</title>
<style type = "text/css">
body
h2
{ background-color: #F0E68C }
{ font-family: arial, sans-serif;
color: blue }
input { background-color: blue;
Posts data to
color: yellow;
database.php
font-weight: bold }
</style>
</head>
<body>
20
<h2> Querying a MySQL database.</h2>
21
<form method = "post" action = "database.php">
22
23
24
25
<div>
<p>Select a field to display:
<!-- add a select box containing options -->
<!-- for SELECT query -->
Jozef Goetz contribution, 2011
Outline
data.html
(1 of 2)
60
<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
(2 of 2)
</div>
34
36
data.html
</select></p>
32
35
Outline
</form>
</body>
37 </html>
Jozef Goetz contribution, 2011
Creates drop-down menu specifying which data to
output to the screen, with * (all data) as the default
selection
61
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?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">
<!-- Fig. 23.15: database.php -->
<!-- Querying a database and displaying the results. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Search Results</title>
<style type = "text/css">
body { font-family: arial, sans-serif;
background-color: #F0E68C }
table { background-color: #ADD8E6 }
td
{ padding-top: 2px;
padding-bottom: 2px;
padding-left: 4px;
padding-right: 4px;
border-width: 1px;
border-style: inset }
</style>
Builds a SELECT query with
</head>
the selection made in
<body>
data.html
<?php
extract( $_POST );
// build SELECT query
$query = "SELECT " . $select . " FROM books";
Jozef Goetz contribution, 2011
Outline
database.php
(1 of 3)
62
29
30
31
// Connect to MySQL
if ( !( $database = mysql_connect( "localhost",
"iw3htp4", "iw3htp4" ) ) )
32
33
die( "Could not connect to database </body></html>" );
34
35
36
// open Products database
if ( !mysql_select_db( "products", $database ) )
die( "Could not open products database </body></html>" );
37
Queries $database with
$query
38
39
// query Products database
if ( !( $result = mysql_query( $query, $database ) ) )
40
{
41
42
43
print( "Could not execute query! <br />" );
die( mysql_error() . "</body></html>" );
} // end if
Returns any error strings from
the database
44
45
46
47
mysql_close( $database );
?><!-- end PHP script -->
<h3>Search Results</h3>
48
49
<table>
<?php
50
51
52
53
54
55
Closes the connection to the
database
// fetch each record in result set
for ( $counter = 0; $row = mysql_fetch_row( $result );
$counter++ )
{
// build table to display results
print( "<tr>" );
56
Returns an array with the
values for each column of the
current row in $result
Jozef Goetz contribution, 2011
Outline
Specifies products as the
database todatabase.php
be queried
(2 of 3)
Connects to database using
server hostname localhost
and username and password
“iw3htp4”
63
foreach ( $row as $key => $value )
57
print( "<td>$value</td>" );
58
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
</h5>
</body>
71 </html>
"$counter“ has the # of
rows;
The same as
mysql_num_rows($result)
Jozef Goetz contribution, 2011
database.php
(3 of 3)
64
23.6 Using Cookies
65
 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.
Jozef Goetz contribution, 2011
1
2
3
4
5
6
<?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">
7
8
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
9
10
cookies.html (1 of 2)
<!-- Fig. 23.16: cookies.html -->
<!-- Gathering data to be written as a cookie. -->
<title>Writing a cookie to the client computer</title>
<style type = "text/css">
11
body
12
13
14
15
16
background-color: #99CCFF }
form
{ font-size: 10pt }
.submit { background-color: #F0E86C;
color: navy;
font-weight: bold }
{ font-family: arial, sans-serif;
17
18
</style>
</head>
19
20
<body>
<h2>Click Write Cookie to save your cookie data.</h2>
21
22
23
24
25
26
27
28
Outline
Posts form data to
cookies.php
<form method = "post" action = "cookies.php">
<div>
<strong>Name:</strong><br />
<input type = "text" name = "Name" /><br />
<strong>Height:</strong><br />
<input type = "text" name = "Height" /><br />
Jozef Goetz contribution, 2011
Creates fields to gather
information to be written into a
cookie
66
29
<strong>Favorite Color:</strong><br />
30
<input type = "text" name = "Color" /><br />
Outline
<input type = "submit" value = "Write Cookie"
cookies.html(2 of 2)
31
32
class = "submit" />
33
</div>
34
35
36
</form>
</body>
37 </html>
Jozef Goetz contribution, 2011
Form field
67
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
// Fig. 23.17: cookies.php
// Writing a cookie to the client.
extract( $_POST );
// write each form field’s value to a cookie and set the
// cookie’s expiration date
setcookie( "Name", $Name, time() + 60 * 60 * 24 * 5 );
setcookie( "Height", $Height, time() + 60 * 60 * 24 * 5 );
setcookie( "Color", $Color, time() + 60 * 60 * 24 * 5 );
?><!-- end PHP script -->
<?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">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Cookie Saved</title>
<style type = "text/css">
body { font-family: arial, sans-serif }
span { color: blue }
</style>
</head>
<body>
<p>The cookie has been set with the following data:</p>
<!-- print each form field’s value -->
<br /><span>Name:</span><?php print( $Name ) ?><br />
Jozef Goetz contribution, 2011
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
68
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>
Jozef Goetz contribution, 2011
Outline
Links to the page that
displays the contents of the
cookie
cookies.php
(2 of 2)
69
Software Engineering Observation 23.2 - 3
 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.
 Cookies should not be used to store
e-mail addresses or private data on a
client’s computer.
Jozef Goetz contribution, 2011
70
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.
Jozef Goetz contribution, 2011
71
72
Fig. 23.18 | IE7’s Cookies directory before a cookie is written.
Fig. 23.19 | IE7’s Cookies directory after a cookie is written.
Jozef Goetz contribution, 2011
23.6 Using Cookies (Cont.)
 PHP creates the superglobal array $_COOKIE,
which contains all the cookie values indexed by
their names.
Jozef Goetz contribution, 2011
73
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?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">
<!-- Fig. 23.20: readCookies.php -->
<!-- Displaying the cookie’s contents. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Read Cookies</title>
<style type = "text/css">
body
{ font-family: arial, sans-serif }
table { border-width: 5px;
border-style: outset }
td
{ padding: 10px }
.key
{ background-color: #F0E68C }
.value { background-color: #FFA500 }
</style>
</head>
<body>
<p>
<strong>The following data is saved in a cookie on your
computer.</strong>
</p>
<table>
<?php
// iterate through array $_COOKIE and print
// name and value of each cookie
Jozef Goetz contribution, 2011
Outline
readCookies.php
(1 of 2)
74
foreach ( $_COOKIE as $key => $value )
28
<td class = 'value' >$value</td></tr>" );
30
?><!-- end PHP script -->
31
32
33
Outline
print( "<tr><td class = 'key' >$key</td>
29
Iterates through all
values in $_COOKIE
</table>
</body>
readCookies.php
34 </html>
(2 of 2)
Jozef Goetz contribution, 2011
75
23.7 Dynamic Content
 Function isset allows you to find out if a variable
has a value.
 A 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.
Jozef Goetz contribution, 2011
76
1
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
2
3
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
// must use form.html from Fig.23.13
<!-- Fig. 23.21: dynamicForm.php -->
6
<!-- Dynamic form. -->
7
8
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
9
10
11
12
<title>Sample form to take user input in XHTML</title>
<style type = "text/css">
td
{ padding-top: 2px;
padding-bottom: 2px;
13
14
15
div
padding-left: 10px;
padding-right: 10px }
{ text-align: center }
16
17
div div
.name
{ font-size: larger }
{ background-color: #ffffaa }
18
19
20
21
22
.email
.phone
.os
.smalltext
.prompt
{
{
{
{
{
font-family: sans-serif;
font-size: smaller }
23
24
25
26
27
28
29
background-color: #ffffbb }
background-color: #ffffcc }
background-color: #ffffdd }
font-size: smaller }
color: blue;
.largeerror { color: red }
.error
{ color: red;
font-size: smaller }
</style>
</head>
Jozef Goetz contribution, 2011
Outline
dynamicForm.php
(1 of 12)
77
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<body>
<?php
extract( $_POST );
$iserror = false;
dynamicForm.php
Outline
(2 of 12)
// array of book titles
$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" );
// array of possible operating systems
$systemlist = array( "Windows XP", "Windows Vista",
"Mac OS X", "Linux", "Other");
// array of name values for the text input fields
$inputlist = array( "fname" => "First Name",
"lname" => "Last Name", "email" => "Email",
"phone" => "Phone" );
// ensure that all fields have been filled in correctly
if ( isset ( $submit ) )
Checks whether the Register button has
{
been pressed
if ( $fname == "" )
{
Checks that the first name field is not blank
$formerrors[ "fnameerror" ] = true;
$iserror = true;
} // end if
Makes an entry in the error array
Sets $iserror to true
Jozef Goetz contribution, 2011
78
58
if ( $lname == "" )
59
60
{
$iserror = true;
61
62
63
64
65
Outline
$formerrors[ "lnameerror" ] = true;
} // end if
if ( $email == "" )
{
Checks that all other
form fields are filled in
correctly
66
$formerrors[ "emailerror" ] = true;
67
$iserror = true;
68
} // end if
69
70
//if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) ) deprecated; error
if ( !preg_match( "/^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$/", $phone ) )
71
{
72
$formerrors[ "phoneerror" ] = true;
73
$iserror = true;
74
} // end if
75
76
if ( !$iserror )
77
{
78
79
80
81
// build INSERT query
$query = "INSERT INTO contacts " .
"( LastName, FirstName, Email, Phone, Book, OS ) " .
"VALUES ( '$lname', '$fname', '$email', " .
82
"'" . quotemeta( $phone ) . "', '$book', '$os' )";
Inserts a backslash before the
parentheses in the phone
number
Jozef Goetz contribution, 2011
dynamicForm.php
(3 of 12)
79
83
Outline
// Connect to MySQL
if ( !( $database = mysql_connect( "localhost",
84
85
"iw3htp4", "iw3htp4" ) ) )
die( "Could not connect to database" );
86
87
88
89
90
lower cases
91
// open MailingList database
if ( !mysql_select_db( "MailingList", $database ) )
dynamicForm.php
//JG error
die( "Could not open MailingList database" );
92
93
// execute query in MailingList database
94
if ( !( $result = mysql_query( $query, $database ) ) )
95
96
{
97
98
die( mysql_error() );
} // end if
99
100
101
102
print( "Could not execute query! <br />" );
mysql_close( $database );
print( "<p>Hi<span class = 'prompt'>
103
104
105
<strong>$fname</strong></span>.
Thank you for completing the survey.<br />
106
107
108
You have been added to the
<span class = 'prompt'>
<strong>$book</strong></span>
109
110
111
112
mailing list.</p>
<strong>The following information has been saved
in our database:</strong><br />
Jozef Goetz contribution, 2011
(4 of 12)
80
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
<table><tr>
<td class =
<td class =
<td class =
<td class =
</tr><tr>
'name'>Name </td>
'email'>Email</td>
'phone'>Phone</td>
'os'>OS</td>
<!-- print each form field’s value -->
<td>$fname $lname</td>
<td>$email</td>
Ends script here if there
<td>$phone</td>
were no errors in the
<td>$os</td>
user input
</tr></table>
<br /><br /><br />
<div><div>
<a href = 'formDatabase.php'>
Click here to view entire database.</a>
</div>This is only a sample form.
You have not been added to a mailing list.
</div></body></html>" );
die();
} // end if
} // end if
print( "<h1>Sample Registration Form.</h1>
Please fill in all fields and click Register." );
Section to be executed only
if $iserror is true
Jozef Goetz contribution, 2011
Outline
dynamicForm.php
(5 of 12)
81
141
142
143
if ( $iserror )
{
print( "<br /><span class = 'largeerror'>
144
145
146
Fields with * need to be filled in properly.</span>" );
} // end if
147
148
149
150
print( "<!-- post form data to form.php -->
<form method = 'post' action = 'dynamicForm.php'>
<img src = 'images/user.gif' alt = 'User' /><br />
<span class = 'prompt'>
151
152
Please fill out the fields below.<br /> </span>
153
<!-- create four text boxes for user input -->" );
154
155
Outline
foreach ( $inputlist as $inputname => $inputalt )
{
156
157
$inputtext = $inputvalues[ $inputname ];
158
159
print( "<img src = 'images/$inputname.gif'
alt = '$inputalt' /><input type = 'text'
160
(6 of 12)
Alerts the user that there
are errors
Iterates through $inputlist
to create the form’s text boxes
// JG remove – not used
Outputs the field’s image
name = '$inputname' value = '" . $$inputname . "' />" );
161
162
163
dynamicForm.php
if ( $formerrors[ ( $inputname )."error" ] == true )
print( "<span class = 'error'>*</span>" );
Sets the name attribute of the
text field to $inputname
164
165
166
167
168
169
print( "<br />" );
} // end foreach
Sets the value attribute of the text field to
the value of the variable with the name of
$inputname’s value
if ( $formerrors[ "phoneerror" ] )
print( "<span class = 'error'>" );
Puts an asterisk next to
fields that have errors
Jozef Goetz contribution, 2011
82
170
171
172
173
else
print("<span class = 'smalltext'>");
print( "Must be in the form (555)555-5555
</span><br /><br />
174
175
176
<img src = 'images/downloads.gif'
alt = 'Publications' /><br />
177
178
179
180
181
182
<span class = 'prompt'>
Which book would you like information about?
</span><br />
183
184
185
186
<!-- create drop-down list containing book names -->
<select name = 'book'>" );
187
188
189
190
191
foreach ( $booklist as $currbook )
{
print( "<option" );
if ( ( $currbook == $book ) )
print( " selected = 'true'" );
192
193
194
Outline
print( ">$currbook</option>" );
} // end foreach
Creates drop-down list
for books, keeping the
previously selected one
selected
195
Jozef Goetz contribution, 2011
dynamicForm.php
(7 of 12)
83
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
print( "</select><br /><br />
<img src = 'images/os.gif' alt = 'Operating System' />
<br /><span class = 'prompt'>
Which operating system are you currently using?
<br /></span>
<!-- create five radio buttons -->" );
Outline
dynamicForm.php
(8 of 12)
$counter = 0;
foreach ( $systemlist as $currsystem )
{
print( "<input type = 'radio' name = 'os'
value = '$currsystem'" );
if ( $currsystem == $os )
print( "checked = 'checked'" );
elseif ( !$os && $counter == 0 )
print( "checked = 'checked'" );
print( " />$currsystem" );
Creates radio buttons for
// put a line break in list of operating operating-system
systems
selection,
keeping the
if ( $counter == 1 ) print( "<br />" );
previously selected
++$counter;
option selected
} // end foreach
Jozef Goetz contribution, 2011
84
223
print( "<!-- create a submit button -->
224
<br /><input type = 'submit' name = 'submit'
225
value = 'Register' /></form></body></html>" );
226
Outline
?><!-- end PHP script -->
dynamicForm.php
(9 of 12)
Jozef Goetz contribution, 2011
85
Outline
dynamicForm.php
(10 of 12)
Jozef Goetz contribution, 2011
86
Outline
dynamicForm.php
(11 of 12)
Jozef Goetz contribution, 2011
87
Outline
dynamicForm.php
(12 of 12)
Jozef Goetz contribution, 2011
88
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?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">
<!-- Fig. 23.22: formDatabase.php -->
<!-- Displaying the MailingList database. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Search Results</title>
<style type = "text/css">
body { font-family: arial, sans-serif;
background-color: #F0E68C }
h3
{ color: blue }
table { background-color: #ADD8E6 }
td
{ padding-top: 2px;
padding-bottom: 2px;
padding-left: 4px;
padding-right: 4px;
border-width: 1px;
border-style: inset }
</style>
</head>
<body>
<?php
extract( $_POST );
// build SELECT query
$query = "SELECT * FROM contacts";
Jozef Goetz contribution, 2011
Outline
89
formDatabase.php
(1 of 3)
Selects all fields from the
contacts database to
display
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Connect to MySQL
if ( !( $database = mysql_connect( "localhost",
"iw3htp4", "iw3htp4" ) ) )
die( "Could not connect to database </body></html>" );
// open MailingList database
if ( !mysql_select_db( "MailingList", $database ) )
die( "Could not open MailingList database </body></html>" );
// query MailingList database
if ( !( $result = mysql_query( $query, $database ) ) )
{
print( "Could not execute query! <br />" );
die( mysql_error() . "</body></html>" );
} // end if
?><!-- end PHP script -->
<h3>Mailing List Contacts</h3>
<table>
<tr>
<td>ID</td>
<td>Last Name</td>
<td>First Name</td>
<td>E-mail Address</td>
<td>Phone Number</td>
<td>Book</td>
<td>Operating System</td>
</tr>
<?php
Jozef Goetz contribution, 2011
Outline
90
formDatabase.php
(2 of 3)
59
// fetch each record in result set
60
for ( $counter = 0; $row = mysql_fetch_row( $result );
Outline
91
$counter++ )
61
{
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>
Jozef Goetz contribution, 2011
23.8 Operator Precedence Chart
 The following table contains a list of PHP
operators in decreasing order of precedence.
Jozef Goetz contribution, 2011
92
93
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.)
Jozef Goetz contribution, 2011
94
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.)
Jozef Goetz contribution, 2011
95
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.)
Jozef Goetz contribution, 2011