php - timlin solutions · in this chapter you will learn: ... 23.3 string processing and regular...

76
1 © 2008 Pearson Education, Inc. All rights reserved. 23 23 PHP

Upload: hanga

Post on 04-Jul-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

1

© 2008 Pearson Education, Inc. All rights reserved.

2323

PHP

2

© 2008 Pearson Education, Inc. All rights reserved.

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

3

© 2008 Pearson Education, Inc. All rights reserved.

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

4

© 2008 Pearson Education, Inc. All rights reserved.

OBJECTIVESIn 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 MySQLdatabases.

5

© 2008 Pearson Education, Inc. All rights reserved.

23.1 Introduction23.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

6

© 2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4 5 <!-- Fig. 23.1: first.php -->

6 <!-- Simple PHP program. -->

7 <html xmlns = "http://www.w3.org/1999/xhtml">

8 <?php

9 $name = "Harvey"; // declaration and initialization

10 ?><!-- end PHP script --> 11 <head> 12 <title>Using PHP document</title> 13 </head> 14 <body style = "font-size: 2em"> 15 <p> 16 <strong> 17 <!-- print variable name’s value --> 18 Welcome to PHP, <?php print( "$name" ); ?>! 19 </strong> 20 </p> 21 </body> 22 </html>

Outline

first.php

7

© 2008 Pearson Education, Inc. All rights reserved.

Common Programming Error 23.1

Failing to precede a variable name with a $ is a syntax error.

8

© 2008 Pearson Education, Inc. All rights reserved.

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.

9

© 2008 Pearson Education, Inc. All rights reserved.

Common Programming Error 23.3

Forgetting to terminate a statement with a semicolon (;) is a syntax error.

10

© 2008 Pearson Education, Inc. All rights reserved.

Type Description

int, integer Whole numbers (i.e., numbers without a decimal point). float, double, real Real numbers (i.e., numbers containing a decimal point). string Text enclosed in either single ('') or double ("") quotes.

[Note: Using double quotes allows PHP to recognize more escape sequences.]

bool, boolean True or false. array Group of elements. object Group of associated data and methods. resource An external source—usually information from a database. NULL No value.

Fig. 23.2 | PHP types.

11

© 2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4 5 <!-- Fig. 23.3: data.php -->

6 <!-- Data type conversion. -->

7 <html xmlns = "http://www.w3.org/1999/xhtml">

8 <head>

9 <title>Data type conversion</title>

10 </head> 11 <body> 12 <?php 13 // declare a string, double and integer 14 $testString = "3.5 seconds"; 15 $testDouble = 79.2; 16 $testInteger = 12; 17 ?><!-- end PHP script --> 18 19 <!-- print each variable’s value and type --> 20 <?php 21 print( "$testString is a(n) " . gettype( $testString ) 22 . "<br />" );

Outline

data.php

(1 of 3)

12

© 2008 Pearson Education, Inc. All rights reserved.

23 print( "$testDouble is a(n) " . gettype( $testDouble ) 24 . "<br />" ); 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 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 $testString <br /><br />" ); 42

Outline

data.php

(2 of 3)

13

© 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 ); 50 print( "<br /><br />after casting, $data is a " . 51 gettype( $data ) ); 52 ?><!-- end PHP script --> 53 </body> 54 </html>

Outline

data.php

(3 of 3)

14

© 2008 Pearson Education, Inc. All rights reserved.

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.

15

© 2008 Pearson Education, Inc. All rights reserved.

Common Programming Error 23.4

Assigning a value to a constant after it is declared is a syntax error.

16

© 2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4 5 <!-- Fig. 23.4: operators.php -->

6 <!-- Using arithmetic operators. -->

7 <html xmlns = "http://www.w3.org/1999/xhtml">

8 <head>

9 <title>Using arithmetic operators</title>

10 </head> 11 <body> 12 <?php 13 $a = 5; 14 print( "The value of variable a is $a <br />" ); 15 16 // define constant VALUE 17 define( "VALUE", 5 ); 18 19 // add constant VALUE to variable $a 20 $a = $a + VALUE; 21 print( "Variable a after adding constant VALUE 22 is $a <br />" ); 23 24 // multiply variable $a by 2 25 $a *= 2; 26 print( "Multiplying variable a by 2 yields $a <br />" ); 27

Outline

operators.php

(1 of 3)

17

© 2008 Pearson Education, Inc. All rights reserved.

28 // test if variable $a is less than 50 29 if ( $a < 50 ) 30 print( "Variable a is less than 50 <br />" ); 31 32 // add 40 to variable $a 33 $a += 40; 34 print( "Variable a after adding 40 is $a <br />" ); 35 36 // test if variable $a is 50 or less 37 if ( $a < 51 ) 38 print( "Variable a is still 50 or less<br />" ); 39 40 // test if variable $a is between 50 and 100, inclusive 41 elseif ( $a < 101 ) 42 print( "Variable a is now between 50 and 100, 43 inclusive<br />" ); 44 else 45 print( "Variable a is now greater than 100 <br />" ); 46 47 // print an uninitialized variable 48 print( "Using a variable before initializing: 49 $nothing <br />" ); // nothing evaluates to "" 50 51 // add constant VALUE to an uninitialized variable 52 $test = $num + VALUE; // num evaluates to 0

Outline

operators.php

(2 of 3)

18

© 2008 Pearson Education, Inc. All rights reserved.

53 print( "An uninitialized variable plus constant 54 VALUE yields $test <br />" ); 55 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 ?><!-- end PHP script --> 61 </body> 62 </html>

Outline

operators.php

(3 of 3)

19

© 2008 Pearson Education, Inc. All rights reserved.

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.

20

© 2008 Pearson Education, Inc. All rights reserved.

PHP keywords

abstract die exit interface require

and do extends isset require_once

array echo __FILE__ __LINE__ return

as else file line static

break elseif final list switch

case empty for __METHOD__ throw

catch enddeclare foreach method try

__CLASS__ endfor __FUNCTION__ new unset

class endforeach function or use

clone endif global php_user_filter var

const endswitch if print while

continue endwhile implements private xor

declare eval include protected

default exception include_once public

Fig. 23.5 | PHP keywords.

21

© 2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4 5 <!-- Fig. 23.6: arrays.php -->

6 <!-- Array manipulation. -->

7 <html xmlns = "http://www.w3.org/1999/xhtml">

8 <head>

9 <title>Array manipulation</title>

10 </head> 11 <body> 12 <?php 13 // create array first 14 print( "<strong>Creating the first array</strong><br />" ); 15 $first[ 0 ] = "zero"; 16 $first[ 1 ] = "one"; 17 $first[ 2 ] = "two"; 18 $first[] = "three"; 19 20 // print each element’s index and value 21 for ( $i = 0; $i < count( $first ); $i++ ) 22 print( "Element $i is $first[$i] <br />" ); 23

Outline

arrays.php

(1 of 4)

22

© 2008 Pearson Education, Inc. All rights reserved.

24 print( "<br /><strong>Creating the second array 25 </strong><br />" ); 26 27 // call function array to create array second 28 $second = array( "zero", "one", "two", "three" ); 29 30 for ( $i = 0; $i < count( $second ); $i++ ) 31 print( "Element $i is $second[$i] <br />" ); 32 33 print( "<br /><strong>Creating the third array 34 </strong><br />" ); 35 36 // assign values to entries using nonnumeric indices 37 $third[ "Amy" ] = 21; 38 $third[ "Bob" ] = 18; 39 $third[ "Carol" ] = 23; 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

Outline

arrays.php

(2 of 4)

23

© 2008 Pearson Education, Inc. All rights reserved.

46 print( "<br /><strong>Creating the fourth array 47 </strong><br />" ); 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" => "eighth", 56 "September" => "ninth", "October" => "tenth", 57 "November" => "eleventh","December" => "twelfth" 58 ); 59 60 // print each element’s name and value 61 foreach ( $fourth as $element => $value ) 62 print( "$element is the $value month <br />" ); 63 ?><!-- end PHP script --> 64 </body> 65 </html>

Outline

arrays.php

(3 of 4)

24

© 2008 Pearson Education, Inc. All rights reserved.

Outline

arrays.php

(4 of 4)

25

© 2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4 5 <!-- Fig. 23.7: compare.php -->

6 <!-- Using the string-comparison operators. -->

7 <html xmlns = "http://www.w3.org/1999/xhtml">

8 <head>

9 <title>String Comparison</title>

10 </head> 11 <body> 12 <?php 13 // create array fruits 14 $fruits = array( "apple", "orange", "banana" ); 15 16 // iterate through each array element 17 for ( $i = 0; $i < count( $fruits ); $i++ ) 18 { 19 // call function strcmp to compare the array element 20 // to string "banana" 21 if ( strcmp( $fruits[ $i ], "banana" ) < 0 ) 22 print( $fruits[ $i ] . " is less than banana " ); 23 elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 ) 24 print( $fruits[ $i ] . " is greater than banana " ); 25 else 26 print( $fruits[ $i ] . " is equal to banana " ); 27 28 // use relational operators to compare each element 29 // to string "apple"

Outline

compare.php

(1 of 2)

26

© 2008 Pearson Education, Inc. All rights reserved.

30 if ( $fruits[ $i ] < "apple" ) 31 print( "and less than apple! <br />" ); 32 elseif ( $fruits[ $i ] > "apple" ) 33 print( "and greater than apple! <br />" ); 34 elseif ( $fruits[ $i ] == "apple" ) 35 print( "and equal to apple! <br />" ); 36 } // end for 37 ?><!-- end PHP script --> 38 </body> 39 </html>

Outline

compare.php

(2 of 2)

27

© 2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4 5 <!-- Fig. 23.8: expression.php -->

6 <!-- Regular expressions. -->

7 <html xmlns = "http://www.w3.org/1999/xhtml">

8 <head>

9 <title>Regular expressions</title>

10 </head> 11 <body> 12 <?php 13 $search = "Now is the time"; 14 print( "Test string is: '$search'<br /><br />" ); 15 16 // call ereg to search for pattern 'Now' in variable search 17 if ( ereg( "Now", $search ) ) 18 print( "String 'Now' was found.<br />" ); 19 20 // search for pattern 'Now' in the beginning of the string 21 if ( ereg( "^Now", $search ) ) 22 print( "String 'Now' found at beginning 23 of the line.<br />" ); 24 25 // search for pattern 'Now' at the end of the string 26 if ( ereg( "Now$", $search ) ) 27 print( "String 'Now' was found at the end 28 of the line.<br />" ); 29

Outline

expression.php

(1 of 2)

28

© 2008 Pearson Education, Inc. All rights reserved.

30 // search for any word ending in 'ow' 31 if ( ereg( "[[:<:]]([a-zA-Z]*ow)[[:>:]]", $search, $match ) ) 32 print( "Word found ending in 'ow': " . 33 $match[ 1 ] . "<br />" ); 34 35 // search for any words beginning with 't' 36 print( "Words beginning with 't' found: "); 37 38 while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]", 39 $search, $match ) ) 40 { 41 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 47 ?><!-- end PHP script --> 48 </body> 49 </html>

Outline

expression.php

(2 of 2)

29

© 2008 Pearson Education, Inc. All rights reserved.

Quantifier Matches

{n} Exactly n times. {m,n} Between m and n times, inclusive. {n,} n or more times. + One or more times (same as {1,}). * Zero or more times (same as {0,}). ? Zero or one time (same as {0,1}).

Fig. 23.9 | Some PHP quantifiers.

30

© 2008 Pearson Education, Inc. All rights reserved.

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.

31

© 2008 Pearson Education, Inc. All rights reserved.

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.

32

© 2008 Pearson Education, Inc. All rights reserved.

1 <?xml version = "1.0" encoding = "utf-8"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4 5 <!-- Fig. 23.12: form.html -->

6 <!-- XHTML form for gathering user input. -->

7 <html xmlns = "http://www.w3.org/1999/xhtml">

8 <head>

9 <title>Sample form to take user input in XHTML</title>

10 <style type = "text/css"> 11 .prompt { color: blue; 12 font-family: sans-serif; 13 font-size: smaller } 14 </style> 15 </head> 16 <body> 17 <h1>Sample Registration Form</h1> 18 <p>Please fill in all fields and click Register.</p> 19 20 <!-- post form data to form.php --> 21 <form method = "post" action = "form.php"> 22 <div> 23 <img src = "images/user.gif" alt = "User" /><br /> 24 <span class = "prompt"> 25 Please fill out the fields below.<br /> 26 </span> 27

Outline

form.html

(1 of 4)

33

© 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 <input type = "text" name = "fname" /><br /> 31 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 /> 37 38 <img src = "images/phone.gif" alt = "Phone" /> 39 <input type = "text" name = "phone" /><br /> 40 41 <span style = "font-size: 10pt"> 42 Must be in the form (555)555-5555</span> 43 <br /><br /> 44 45 <img src = "images/downloads.gif" 46 alt = "Publications" /><br /> 47 48 <span class = "prompt"> 49 Which book would you like information about? 50 </span><br /> 51 52 <!-- create drop-down list containing book names --> 53 <select name = "book">

Outline

form.html

(2 of 4)

34

© 2008 Pearson Education, Inc. All rights reserved.

54 <option>Internet and WWW How to Program 4e</option> 55 <option>C++ How to Program 6e</option> 56 <option>Java How to Program 7e</option> 57 <option>Visual Basic 2005 How to Program 3e</option> 58 </select> 59 <br /><br /> 60 61 <img src = "images/os.gif" alt = "Operating System" /> 62 <br /><span class = "prompt"> 63 Which operating system are you currently using? 64 <br /></span> 65 66 <!-- create five radio buttons --> 67 <input type = "radio" name = "os" value = "Windows XP" 68 checked = "checked" /> Windows XP 69 <input type = "radio" name = "os" value = 70 "Windows Vista" /> Windows Vista<br /> 71 <input type = "radio" name = "os" value = 72 "Mac OS X" /> Mac OS X 73 <input type = "radio" name = "os" value = "Linux" /> Linux 74 <input type = "radio" name = "os" value = "Other" /> 75 Other<br /> 76

Outline

form.html

(3 of 4)

35

© 2008 Pearson Education, Inc. All rights reserved.

77 <!-- create a submit button --> 78 <input type = "submit" value = "Register" /> 79 </div> 80 </form> 81 </body> 82 </html>

Outline

form.html

(4 of 4)

36

© 2008 Pearson Education, Inc. All rights reserved.

Good Programming Practice 23.1

Use meaningful XHTML object names for input fields. This makes PHP scripts that retrieve form data easier to understand.

37

© 2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4 5 <!-- Fig. 23.13: form.php -->

6 <!-- Process information sent from form.html. -->

7 <html xmlns = "http://www.w3.org/1999/xhtml">

8 <head>

9 <title>Form Validation</title>

10 <style type = "text/css"> 11 body { font-family: arial, sans-serif } 12 div { font-size: 10pt; 13 text-align: center } 14 table { border: 0 } 15 td { padding-top: 2px; 16 padding-bottom: 2px; 17 padding-left: 10px; 18 padding-right: 10px } 19 .error { color: red } 20 .distinct { color: blue } 21 .name { background-color: #ffffaa } 22 .email { background-color: #ffffbb } 23 .phone { background-color: #ffffcc } 24 .os { background-color: #ffffdd } 25 </style> 26 </head> 27 <body>

Outline

form.php

(1 of 5)

38

© 2008 Pearson Education, Inc. All rights reserved.

28 <?php 29 extract( $_POST ); 30 31 // determine whether phone number is valid and print 32 // an error message if not 33 if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) ) 34 { 35 print( "<p><span class = 'error'> 36 Invalid phone number</span><br /> 37 A valid phone number must be in the form 38 <strong>(555)555-5555</strong><br /> 39 <span class = 'distinct'> 40 Click the Back button, enter a valid phone 41 number and resubmit.<br /><br /> 42 Thank You.</span></p>" ); 43 die( "</body></html>" ); // terminate script execution 44 } 45 ?><!-- end PHP script --> 46 <p>Hi 47 <span class = "distinct"> 48 <strong><?php print( "$fname" ); ?></strong> 49 </span>. 50 Thank you for completing the survey.<br /> 51 You have been added to the 52 <span class = "distinct"> 53 <strong><?php print( "$book " ); ?></strong> 54 </span> 55 mailing list.

Outline

form.php

(2 of 5)

39

© 2008 Pearson Education, Inc. All rights reserved.

56 </p> 57 <p><strong>The following information has been saved 58 in our database:</strong></p> 59 <table> 60 <tr> 61 <td class = "name">Name </td> 62 <td class = "email">Email</td> 63 <td class = "phone">Phone</td> 64 <td class = "os">OS</td> 65 </tr> 66 <tr> 67 <?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> 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>

Outline

form.php

(3 of 5)

40

© 2008 Pearson Education, Inc. All rights reserved.

Outline

form.php

(4 of 5)

41

© 2008 Pearson Education, Inc. All rights reserved.

Outline

form.php

(5 of 5)

42

© 2008 Pearson Education, Inc. All rights reserved.

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.

43

© 2008 Pearson Education, Inc. All rights reserved.

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>").

44

© 2008 Pearson Education, Inc. All rights reserved.

1 <?xml version = "1.0" encoding = "utf-8"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4 5 <!-- Fig. 23.14: data.html -->

6 <!-- Form to query a MySQL database. -->

7 <html xmlns = "http://www.w3.org/1999/xhtml">

8 <head>

9 <title>Sample Database Query</title>

10 <style type = "text/css"> 11 body { background-color: #F0E68C } 12 h2 { font-family: arial, sans-serif; 13 color: blue } 14 input { background-color: blue; 15 color: yellow; 16 font-weight: bold } 17 </style> 18 </head> 19 <body> 20 <h2> Querying a MySQL database.</h2> 21 <form method = "post" action = "database.php"> 22 <div> 23 <p>Select a field to display: 24 <!-- add a select box containing options --> 25 <!-- for SELECT query -->

Outline

data.html

(1 of 2)

45

© 2008 Pearson Education, Inc. All rights reserved.

26 <select name = "select"> 27 <option selected = "selected">*</option> 28 <option>ID</option> 29 <option>Title</option> 30 <option>Category</option> 31 <option>ISBN</option> 32 </select></p> 33 <input type = "submit" value = "Send Query" /> 34 </div> 35 </form> 36 </body> 37 </html>

Outline

data.html

(2 of 2)

46

© 2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4 5 <!-- Fig. 23.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"> 11 body { font-family: arial, sans-serif; 12 background-color: #F0E68C } 13 table { background-color: #ADD8E6 } 14 td { padding-top: 2px; 15 padding-bottom: 2px; 16 padding-left: 4px; 17 padding-right: 4px; 18 border-width: 1px; 19 border-style: inset } 20 </style> 21 </head> 22 <body> 23 <?php 24 extract( $_POST ); 25 26 // build SELECT query 27 $query = "SELECT " . $select . " FROM books"; 28

Outline

database.php

(1 of 3)

47

© 2008 Pearson Education, Inc. All rights reserved.

29 // Connect to MySQL 30 if ( !( $database = mysql_connect( "localhost", 31 "iw3htp4", "iw3htp4" ) ) ) 32 die( "Could not connect to database </body></html>" ); 33 34 // open Products database 35 if ( !mysql_select_db( "products", $database ) ) 36 die( "Could not open products database </body></html>" ); 37 38 // query Products database 39 if ( !( $result = mysql_query( $query, $database ) ) ) 40 { 41 print( "Could not execute query! <br />" ); 42 die( mysql_error() . "</body></html>" ); 43 } // end if 44 45 mysql_close( $database ); 46 ?><!-- end PHP script --> 47 <h3>Search Results</h3> 48 <table> 49 <?php 50 // fetch each record in result set 51 for ( $counter = 0; $row = mysql_fetch_row( $result ); 52 $counter++ ) 53 { 54 // build table to display results 55 print( "<tr>" ); 56

Outline

database.php

(2 of 3)

48

© 2008 Pearson Education, Inc. All rights reserved.

57 foreach ( $row as $key => $value ) 58 print( "<td>$value</td>" ); 59 60 print( "</tr>" ); 61 } // end for 62 ?><!-- end PHP script --> 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 </h5> 70 </body> 71 </html>

Outline

database.php

(3 of 3)

49

© 2008 Pearson Education, Inc. All rights reserved.

1 <?xml version = "1.0" encoding = "utf-8"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4 5 <!-- 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 body { font-family: arial, sans-serif; 12 background-color: #99CCFF } 13 form { font-size: 10pt } 14 .submit { background-color: #F0E86C; 15 color: navy; 16 font-weight: bold } 17 </style> 18 </head> 19 <body> 20 <h2>Click Write Cookie to save your cookie data.</h2> 21 <form method = "post" action = "cookies.php"> 22 <div> 23 <strong>Name:</strong><br /> 24 <input type = "text" name = "Name" /><br /> 25 26 <strong>Height:</strong><br /> 27 <input type = "text" name = "Height" /><br /> 28

Outline

cookies.html

(1 of 2)

50

© 2008 Pearson Education, Inc. All rights reserved.

29 <strong>Favorite Color:</strong><br /> 30 <input type = "text" name = "Color" /><br /> 31 32 <input type = "submit" value = "Write Cookie" 33 class = "submit" /> 34 </div> 35 </form> 36 </body> 37 </html>

Outline

cookies.html

(2 of 2)

51

© 2008 Pearson Education, Inc. All rights reserved.

1 <?php

2 // Fig. 23.17: cookies.php

3 // Writing a cookie to the client.

4 extract( $_POST );

5 6 // write each form field’s value to a cookie and set the

7 // cookie’s expiration date

8 setcookie( "Name", $Name, time() + 60 * 60 * 24 * 5 );

9 setcookie( "Height", $Height, time() + 60 * 60 * 24 * 5 );

10 setcookie( "Color", $Color, time() + 60 * 60 * 24 * 5 ); 11 ?><!-- end PHP script --> 12 13 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?> 14 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 15 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 16 17 <html xmlns = "http://www.w3.org/1999/xhtml"> 18 <head> 19 <title>Cookie Saved</title> 20 <style type = "text/css"> 21 body { font-family: arial, sans-serif } 22 span { color: blue } 23 </style> 24 </head> 25 <body> 26 <p>The cookie has been set with the following data:</p> 27 28 <!-- print each form field’s value --> 29 <br /><span>Name:</span><?php print( $Name ) ?><br />

Outline

cookies.php

(1 of 2)

52

© 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> 35 to read the saved cookie.</p> 36 </body> 37 </html>

Outline

cookies.php

(2 of 2)

53

© 2008 Pearson Education, Inc. All rights reserved.

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.

54

© 2008 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 23.3

Cookies should not be used to store e-mail addresses or private data on a client’s computer.

55

© 2008 Pearson Education, Inc. All rights reserved.

Fig. 23.18 | IE7’s Cookies directory before a cookie is written.

56

© 2008 Pearson Education, Inc. All rights reserved.

Fig. 23.19 | IE7’s Cookies directory after a cookie is written.

57

© 2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4 5 <!-- Fig. 23.20: readCookies.php -->

6 <!-- Displaying the cookie’s contents. -->

7 <html xmlns = "http://www.w3.org/1999/xhtml">

8 <head>

9 <title>Read Cookies</title>

10 <style type = "text/css"> 11 body { font-family: arial, sans-serif } 12 table { border-width: 5px; 13 border-style: outset } 14 td { padding: 10px } 15 .key { background-color: #F0E68C } 16 .value { background-color: #FFA500 } 17 </style> 18 </head> 19 <body> 20 <p> 21 <strong>The following data is saved in a cookie on your 22 computer.</strong> 23 </p> 24 <table> 25 <?php 26 // iterate through array $_COOKIE and print 27 // name and value of each cookie

Outline

readCookies.php

(1 of 2)

58

© 2008 Pearson Education, Inc. All rights reserved.

28 foreach ( $_COOKIE as $key => $value ) 29 print( "<tr><td class = 'key' >$key</td> 30 <td class = 'value' >$value</td></tr>" ); 31 ?><!-- end PHP script --> 32 </table> 33 </body> 34 </html>

Outline

readCookies.php

(2 of 2)

59

© 2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4 5 <!-- Fig. 23.21: dynamicForm.php -->

6 <!-- Dynamic form. -->

7 <html xmlns = "http://www.w3.org/1999/xhtml">

8 <head>

9 <title>Sample form to take user input in XHTML</title>

10 <style type = "text/css"> 11 td { padding-top: 2px; 12 padding-bottom: 2px; 13 padding-left: 10px; 14 padding-right: 10px } 15 div { text-align: center } 16 div div { font-size: larger } 17 .name { background-color: #ffffaa } 18 .email { background-color: #ffffbb } 19 .phone { background-color: #ffffcc } 20 .os { background-color: #ffffdd } 21 .smalltext { font-size: smaller } 22 .prompt { color: blue; 23 font-family: sans-serif; 24 font-size: smaller } 25 .largeerror { color: red } 26 .error { color: red; 27 font-size: smaller } 28 </style> 29 </head>

Outline

dynamicForm.php

(1 of 12)

60

© 2008 Pearson Education, Inc. All rights reserved.

30 <body> 31 <?php 32 extract( $_POST ); 33 $iserror = false; 34 35 // array of book titles 36 $booklist = array( "Internet and WWW How to Program 4e", 37 "C++ How to Program 6e", "Java How to Program 7e", 38 "Visual Basic 2005 How to Program 3e" ); 39 40 // array of possible operating systems 41 $systemlist = array( "Windows XP", "Windows Vista", 42 "Mac OS X", "Linux", "Other"); 43 44 // array of name values for the text input fields 45 $inputlist = array( "fname" => "First Name", 46 "lname" => "Last Name", "email" => "Email", 47 "phone" => "Phone" ); 48 49 // ensure that all fields have been filled in correctly 50 if ( isset ( $submit ) ) 51 { 52 if ( $fname == "" ) 53 { 54 $formerrors[ "fnameerror" ] = true; 55 $iserror = true; 56 } // end if 57

Outline

dynamicForm.php

(2 of 12)

61

© 2008 Pearson Education, Inc. All rights reserved.

58 if ( $lname == "" ) 59 { 60 $formerrors[ "lnameerror" ] = true; 61 $iserror = true; 62 } // end if 63 64 if ( $email == "" ) 65 { 66 $formerrors[ "emailerror" ] = true; 67 $iserror = true; 68 } // end if

69 70 if ( !ereg( "^\([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 // build INSERT query 79 $query = "INSERT INTO contacts " . 80 "( LastName, FirstName, Email, Phone, Book, OS ) " . 81 "VALUES ( '$lname', '$fname', '$email', " . 82 "'" . quotemeta( $phone ) . "', '$book', '$os' )";

Outline

dynamicForm.php

(3 of 12)

62

© 2008 Pearson Education, Inc. All rights reserved.

83 84 // Connect to MySQL 85 if ( !( $database = mysql_connect( "localhost", 86 "iw3htp4", "iw3htp4" ) ) ) 87 die( "Could not connect to database" ); 88 89 // open MailingList database 90 if ( !mysql_select_db( "MailingList", $database ) ) 91 die( "Could not open MailingList database" ); 92 93 // execute query in MailingList database 94 if ( !( $result = mysql_query( $query, $database ) ) ) 95 { 96 print( "Could not execute query! <br />" ); 97 die( mysql_error() ); 98 } // end if 99 100 mysql_close( $database ); 101 102 print( "<p>Hi<span class = 'prompt'> 103 <strong>$fname</strong></span>. 104 Thank you for completing the survey.<br /> 105 106 You have been added to the 107 <span class = 'prompt'> 108 <strong>$book</strong></span> 109 mailing list.</p> 110 <strong>The following information has been saved 111 in our database:</strong><br /> 112

Outline

dynamicForm.php

(4 of 12)

63

© 2008 Pearson Education, Inc. All rights reserved.

113 <table><tr> 114 <td class = 'name'>Name </td> 115 <td class = 'email'>Email</td> 116 <td class = 'phone'>Phone</td> 117 <td class = 'os'>OS</td> 118 </tr><tr> 119 120 <!-- print each form field’s value --> 121 <td>$fname $lname</td> 122 <td>$email</td> 123 <td>$phone</td> 124 <td>$os</td> 125 </tr></table> 126 127 <br /><br /><br /> 128 <div><div> 129 <a href = 'formDatabase.php'> 130 Click here to view entire database.</a> 131 </div>This is only a sample form. 132 You have not been added to a mailing list. 133 </div></body></html>" ); 134 die(); 135 } // end if 136 } // end if 137 138 print( "<h1>Sample Registration Form.</h1> 139 Please fill in all fields and click Register." ); 140

Outline

dynamicForm.php

(5 of 12)

64

© 2008 Pearson Education, Inc. All rights reserved.

141 if ( $iserror ) 142 { 143 print( "<br /><span class = 'largeerror'> 144 Fields with * need to be filled in properly.</span>" ); 145 } // end if 146 147 print( "<!-- post form data to form.php --> 148 <form method = 'post' action = 'dynamicForm.php'> 149 <img src = 'images/user.gif' alt = 'User' /><br /> 150 <span class = 'prompt'> 151 Please fill out the fields below.<br /> </span> 152 153 <!-- create four text boxes for user input -->" ); 154 foreach ( $inputlist as $inputname => $inputalt ) 155 { 156 $inputtext = $inputvalues[ $inputname ]; 157 158 print( "<img src = 'images/$inputname.gif' 159 alt = '$inputalt' /><input type = 'text' 160 name = '$inputname' value = '" . $$inputname . "' />" ); 161 162 if ( $formerrors[ ( $inputname )."error" ] == true ) 163 print( "<span class = 'error'>*</span>" ); 164 165 print( "<br />" ); 166 } // end foreach 167 168 if ( $formerrors[ "phoneerror" ] ) 169 print( "<span class = 'error'>" );

Outline

dynamicForm.php

(6 of 12)

65

© 2008 Pearson Education, Inc. All rights reserved.

170 else 171 print("<span class = 'smalltext'>"); 172 173 print( "Must be in the form (555)555-5555 174 </span><br /><br /> 175 176 <img src = 'images/downloads.gif' 177 alt = 'Publications' /><br /> 178 179 <span class = 'prompt'> 180 Which book would you like information about? 181 </span><br /> 182 183 <!-- create drop-down list containing book names --> 184 <select name = 'book'>" ); 185 186 foreach ( $booklist as $currbook ) 187 { 188 print( "<option" ); 189 190 if ( ( $currbook == $book ) ) 191 print( " selected = 'true'" ); 192 193 print( ">$currbook</option>" ); 194 } // end foreach 195

Outline

dynamicForm.php

(7 of 12)

66

© 2008 Pearson Education, Inc. All rights reserved.

196 print( "</select><br /><br /> 197 <img src = 'images/os.gif' alt = 'Operating System' /> 198 <br /><span class = 'prompt'> 199 Which operating system are you currently using? 200 <br /></span> 201 202 <!-- create five radio buttons -->" ); 203 204 $counter = 0; 205 206 foreach ( $systemlist as $currsystem ) 207 { 208 print( "<input type = 'radio' name = 'os' 209 value = '$currsystem'" ); 210 211 if ( $currsystem == $os ) 212 print( "checked = 'checked'" ); 213 elseif ( !$os && $counter == 0 ) 214 print( "checked = 'checked'" ); 215 216 print( " />$currsystem" ); 217 218 // put a line break in list of operating systems 219 if ( $counter == 1 ) print( "<br />" ); 220 ++$counter; 221 } // end foreach 222

Outline

dynamicForm.php

(8 of 12)

67

© 2008 Pearson Education, Inc. All rights reserved.

223 print( "<!-- create a submit button --> 224 <br /><input type = 'submit' name = 'submit' 225 value = 'Register' /></form></body></html>" ); 226 ?><!-- end PHP script -->

Outline

dynamicForm.php

(9 of 12)

68

© 2008 Pearson Education, Inc. All rights reserved.

Outline

dynamicForm.php

(10 of 12)

69

© 2008 Pearson Education, Inc. All rights reserved.

Outline

dynamicForm.php

(11 of 12)

70

© 2008 Pearson Education, Inc. All rights reserved.

Outline

dynamicForm.php

(12 of 12)

71

© 2008 Pearson Education, Inc. All rights reserved.

1 <?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4 5 <!-- Fig. 23.22: formDatabase.php -->

6 <!-- Displaying the MailingList database. -->

7 <html xmlns = "http://www.w3.org/1999/xhtml">

8 <head>

9 <title>Search Results</title>

10 <style type = "text/css"> 11 body { font-family: arial, sans-serif; 12 background-color: #F0E68C } 13 h3 { color: blue } 14 table { background-color: #ADD8E6 } 15 td { padding-top: 2px; 16 padding-bottom: 2px; 17 padding-left: 4px; 18 padding-right: 4px; 19 border-width: 1px; 20 border-style: inset } 21 </style> 22 </head> 23 <body> 24 <?php 25 extract( $_POST ); 26 27 // build SELECT query 28 $query = "SELECT * FROM contacts"; 29

Outline

formDatabase.php

(1 of 3)

72

© 2008 Pearson Education, Inc. All rights reserved.

30 // Connect to MySQL 31 if ( !( $database = mysql_connect( "localhost", 32 "iw3htp4", "iw3htp4" ) ) ) 33 die( "Could not connect to database </body></html>" ); 34 35 // open MailingList database 36 if ( !mysql_select_db( "MailingList", $database ) ) 37 die( "Could not open MailingList database </body></html>" ); 38 39 // query MailingList database 40 if ( !( $result = mysql_query( $query, $database ) ) ) 41 { 42 print( "Could not execute query! <br />" ); 43 die( mysql_error() . "</body></html>" ); 44 } // end if 45 ?><!-- end PHP script --> 46 47 <h3>Mailing List Contacts</h3> 48 <table> 49 <tr> 50 <td>ID</td> 51 <td>Last Name</td> 52 <td>First Name</td> 53 <td>E-mail Address</td> 54 <td>Phone Number</td> 55 <td>Book</td> 56 <td>Operating System</td> 57 </tr> 58 <?php

Outline

formDatabase.php

(2 of 3)

73

© 2008 Pearson Education, Inc. All rights reserved.

59 // fetch each record in result set 60 for ( $counter = 0; $row = mysql_fetch_row( $result ); 61 $counter++ ) 62 { 63 // build table to display results 64 print( "<tr>" ); 65 66 foreach ( $row as $key => $value ) 67 print( "<td>$value</td>" ); 68 69 print( "</tr>" ); 70 } // end for 71 72 mysql_close( $database ); 73 ?><!-- end PHP script --> 74 </table> 75 </body> 76 </html>

Outline

formDatabase.php

(3 of 3)

74

© 2008 Pearson Education, Inc. All rights reserved.

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.)

75

© 2008 Pearson Education, Inc. All rights reserved.

Operator Type Associativity

<<

>>

bitwise shift left

bitwise shift right

left to right

<

>

<=

>=

less than greater than less than or equal greater than or equal

none

==

!=

===

!==

equal not equal identical not identical

none

& 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.)

76

© 2008 Pearson Education, Inc. All rights reserved.

Operator Type Associativity

=

+=

-=

*=

/=

&=

|=

^=

.=

<<=

>>=

assignment addition assignment subtraction assignment multiplication assignment division assignment bitwise AND assignment bitwise OR assignment bitwise exclusive OR assignment concatenation assignment bitwise shift left assignment bitwise shift right assignment

left to right

and logical AND left to right xor exclusive OR left to right or logical OR left to right , list left to right

Fig. 23.23 | PHP operator precedence and associativity. (Part 3 of 3.)