Download Document

Document related concepts

Extensible Storage Engine wikipedia , lookup

Relational model wikipedia , lookup

Clusterpoint wikipedia , lookup

Functional Database Model wikipedia , lookup

Object-relational impedance mismatch wikipedia , lookup

Database model wikipedia , lookup

Transcript
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
print( "$testInteger is a(n) " . gettype( $testInteger)
26
. "<br />" );
27
?><!-- end PHP script -->
28
<br />
29
converting to other data types:<br />
30
<?php
Outline
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
3
4
5
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
6
7
8
9
<!-- Using arithmetic operators. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Using arithmetic operators</title>
Outline
<!-- Fig. 23.4: operators.php -->
10
</head>
11
12
<body>
<?php
operators.php
(1 of 3)
13
14
$a = 5;
print( "The value of variable a is $a <br />" );
15
16
// define constant VALUE
Creates the named
constant VALUE with a
value of 5
17
18
define( "VALUE", 5 );
19
20
21
// add constant VALUE to variable $a
$a = $a + VALUE;
print( "Variable a after adding constant VALUE
22
23
21
is $a <br />" );
Equivalent to $a = $a * 2
24
25
// multiply variable $a by 2
$a *= 2;
26
27
print( "Multiplying variable a by 2 yields $a <br />" );
 2008 Pearson Education,
Inc. All rights reserved.
28
29
30
// test if variable $a is less than 50
if ( $a < 50 )
22
print( "Variable a is less than 50 <br />" );
Outline
31
32
// add 40 to variable $a
33
34
35
$a += 40;
print( "Variable a after adding 40 is $a <br />" );
36
// test if variable $a is 50 or less
37
38
if ( $a < 51 )
print( "Variable a is still 50 or less<br />" );
Uses a comparison operator
with a variable and an integer
operators.php
(2 of 3)
39
40
// test if variable $a is between 50 and 100, inclusive
41
elseif ( $a < 101 )
42
43
44
45
46
47
48
49
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 ""
50
51
// add constant VALUE to an uninitialized variable
52
$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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?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">
28
Outline
<!-- Fig. 23.6: arrays.php -->
<!-- Array manipulation. -->
arrays.php
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
(1 of 4)
<title>Array manipulation</title>
Automatically creates
</head>
array $first
<body>
<?php
Sets the first element of array
// create array first
print( "<strong>Creating the first array</strong><br />" );$first to the string “zero”
$first[ 0 ] = "zero";
“three” is appended to
$first[ 1 ] = "one";
$first[ 2 ] = "two";
the end of array $first
$first[] = "three";
// 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
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?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.7: compare.php -->
<!-- Using the string-comparison operators. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>String Comparison</title>
</head>
<body>
<?php
// create array fruits
$fruits = array( "apple", "orange", "banana" );
// iterate through each array element
for ( $i = 0; $i < count( $fruits ); $i++ )
{
19
20
21
22
23
24
// call function strcmp to compare the array element
// to string "banana"
if ( strcmp( $fruits[ $i ], "banana" ) < 0 )
print( $fruits[ $i ] . " is less than banana " );
elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 )
print( $fruits[ $i ] . " is greater than banana " );
25
26
27
28
29
else
print( $fruits[ $i ] . " is equal to banana " );
33
Outline
compare.php
(1 of 2)
Checks whether the ith
element of the fruits
array preceeds the string
banana
// use relational operators to compare each element
// to string "apple"
 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.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.
36
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
3
4
5
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
6
7
8
9
<!-- 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>
10
11
12
13
14
15
16
37
<!-- Fig. 23.12: form.html -->
form.html
(1 of 4)
<style type = "text/css">
.prompt { color: blue;
font-family: sans-serif;
font-size: smaller }
</style>
</head>
<body>
Appends form data to the
browser request that
contains the protocol and
the URL of the requested
resource
17
18
<h1>Sample Registration Form</h1>
<p>Please fill in all fields and click Register.</p>
19
20
21
<!-- post form data to form.php -->
<form method = "post" action = "form.php">
22
23
Outline
Form data is posted to
form.php to be processed
<div>
<img src = "images/user.gif" alt = "User" /><br />
24
25
<span class = "prompt">
Please fill out the fields below.<br />
26
27
</span>
 2008 Pearson Education,
Inc. All rights reserved.
28
<!-- create four text boxes for user input -->
29
<img src = "images/fname.gif" alt = "First Name" />
30
31
<input type = "text" name = "fname" /><br />
32
<img src = "images/lname.gif" alt = "Last Name" />
33
<input type = "text" name = "lname" /><br />
34
35
<img src = "images/email.gif" alt = "Email" />
36
<input type = "text" name = "email" /><br />
38
Outline
form.html
(2 of 4)
37
38
39
<img src = "images/phone.gif" alt = "Phone" />
<input type = "text" name = "phone" /><br />
40
41
<span style = "font-size: 10pt">
42
43
44
Must be in the form (555)555-5555</span>
<br /><br />
45
<img src = "images/downloads.gif"
46
47
48
alt = "Publications" /><br />
49
Creates form fields
<span class = "prompt">
Which book would you like information about?
50
</span><br />
51
52
<!-- create drop-down list containing book names -->
53
<select name = "book">
Creates drop-down list
with book names
 2008 Pearson Education,
Inc. All rights reserved.
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<option>Internet and WWW How to Program 4e</option>
<option>C++ How to Program 6e</option>
<option>Java How to Program 7e</option>
<option>Visual Basic 2005 How to Program 3e</option>
</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 -->
<input type = "radio" name = "os" value = "Windows XP"
checked = "checked" /> Windows XP
<input type = "radio" name = "os" value =
"Windows Vista" /> Windows Vista<br />
<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 />
39
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
40
Outline
</form>
</body>
82 </html>
form.html
(4 of 4)
 2008 Pearson Education,
Inc. All rights reserved.
41
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.
42
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.
43
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.
44
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">
45
Outline
4
5
<!-- Fig. 23.14: data.html -->
6
7
8
<!-- Form to query a MySQL database. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
9
<title>Sample Database Query</title>
10
11
<style type = "text/css">
body { background-color: #F0E68C }
12
h2
color: blue }
input { background-color: blue;
color: yellow;
font-weight: bold }
15
16
17
(1 of 2)
{ font-family: arial, sans-serif;
13
14
data.html
Posts data to
database.php
</style>
18
</head>
19
20
21
<body>
<h2> Querying a MySQL database.</h2>
<form method = "post" action = "database.php">
22
23
<div>
<p>Select a field to display:
24
<!-- add a select box containing options -->
25
<!-- 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
46
</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
2
3
4
5
<?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">
11
12
13
body
14
15
16
td
database.php
(1 of 3)
{ font-family: arial, sans-serif;
background-color: #F0E68C }
table { background-color: #ADD8E6 }
{ padding-top: 2px;
padding-bottom: 2px;
padding-left: 4px;
17
18
padding-right: 4px;
border-width: 1px;
19
20
21
22
23
24
border-style: inset }
27
28
Outline
<!-- Fig. 23.15: database.php -->
6 <!-- Querying a database and displaying the results. -->
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
<head>
9
<title>Search Results</title>
10
<style type = "text/css">
25
26
47
</style>
</head>
<body>
<?php
extract( $_POST );
Builds a SELECT query
with the selection made
in data.html
// build SELECT query
$query = "SELECT " . $select . " FROM books";
 2008 Pearson Education,
Inc. All rights reserved.
29
30
31
32
33
// Connect to MySQL
if ( !( $database = mysql_connect( "localhost",
"iw3htp4", "iw3htp4" ) ) )
die( "Could not connect to database </body></html>" );
34
35
36
37
38
// open Products database
if ( !mysql_select_db( "products", $database ) )
die( "Could not open products database </body></html>" );
39
40
41
if ( !( $result = mysql_query( $query, $database ) ) )
{
print( "Could not execute query! <br />" );
42
43
44
die( mysql_error() . "</body></html>" );
} // end if
Returns
// query Products database
any error strings
from the database
45
46
mysql_close( $database );
?><!-- end PHP script -->
47
48
49
50
51
52
Closes the connection to
<h3>Search Results</h3>
the database
<table>
<?php
// fetch each record in result set
for ( $counter = 0; $row = mysql_fetch_row( $result );
$counter++ )
53
54
55
56
48
Outline
database.php
(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
{
// build table to display results
print( "<tr>" );
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
49
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.
50
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
2
3
4
5
<?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">
51
Outline
<!-- Fig. 23.16: cookies.html -->
6 <!-- Gathering data to be written as a cookie. -->
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
<head>
9
<title>Writing a cookie to the client computer</title>
10
<style type = "text/css">
11
12
13
body
14
15
16
.submit { background-color: #F0E86C;
color: navy;
font-weight: bold }
form
Posts form data to
cookies.php
</style>
</head>
19
20
21
22
23
24
<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 />
27
28
(1 of 2)
{ font-family: arial, sans-serif;
background-color: #99CCFF }
{ font-size: 10pt }
17
18
25
26
cookies.html
Creates fields to gather
information to be written
into a cookie
<strong>Height:</strong><br />
<input type = "text" name = "Height" /><br />
 2008 Pearson Education,
Inc. All rights reserved.
29
<strong>Favorite Color:</strong><br />
30
<input type = "text" name = "Color" /><br />
52
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
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?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">
53
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
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
19
20
21
22
23
24
<title>Cookie Saved</title>
<style type = "text/css">
body { font-family: arial, sans-serif }
span { color: blue }
</style>
</head>
25
26
27
28
29
<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 />
 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
54
Outline
cookies.php
(2 of 2)
 2008 Pearson Education,
Inc. All rights reserved.
55
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.
56
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.
57
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.
58
Fig. 23.18 | IE7’s Cookies directory before a cookie is written.
 2008 Pearson Education, Inc. All rights reserved.
59
Fig. 23.19 | IE7’s Cookies directory after a cookie is written.
 2008 Pearson Education, Inc. All rights reserved.
60
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
3
4
5
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
6
7
8
9
<!-- Displaying the cookie’s contents. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Read Cookies</title>
10
Outline
<!-- Fig. 23.20: readCookies.php -->
readCookies.php
(1 of 2)
<style type = "text/css">
body
table
{ font-family: arial, sans-serif }
{ border-width: 5px;
13
14
td
border-style: outset }
{ padding: 10px }
15
16
.key
{ background-color: #F0E68C }
.value { background-color: #FFA500 }
11
12
17
18
</style>
</head>
19
20
21
<body>
<p>
<strong>The following data is saved in a cookie on your
computer.</strong>
22
23
</p>
24
25
<table>
<?php
26
27
61
// iterate through array $_COOKIE and print
// 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
62
</table>
</body>
Iterates through
all values in
$_COOKIE
readCookies.php
34 </html>
(2 of 2)
 2008 Pearson Education,
Inc. All rights reserved.