Your SlideShare is downloading. ×
  • Like
Php NotesBeginner
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Php NotesBeginner

  • 2,994 views
Published

 

Published in Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
2,994
On SlideShare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
12
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. 1 PHP Notes Outline 26.1 Introduction 26.2 PHP 26.3 String Processing and Regular Expressions 26.4 Viewing Client/Server Environment Variables 26.5 Form Processing and Business Logic 26.6 Verifying a Username and Password 26.7 Connecting to a Database 26.8 Cookies 26.9 Dynamic Content in PHP 26.10 Operator Precedence 26.11 Web Resources2003 Prentice Hall, Inc. All rights reserved.
  • 2. 2 Objectives In this chapter, you will learn: – To understand PHP data types, operators, arrays and control structures. – To understand string processing and regular expressions in PHP. – To construct programs that process form data. – To be able to read and write client data using cookies. – To construct programs that interact with MySQL databases.2003 Prentice Hall, Inc. All rights reserved.
  • 3. 3 26.1 Introduction • PHP – PHP: Hypertext Preprocessor – Originally called “Personal Home Page Tools” – Popular server-side scripting technology – Open-source • Anyone may view, modify and redistribute source code • Supported freely by community – Platform independent2003 Prentice Hall, Inc. All rights reserved.
  • 4. 4 26.2 PHP • Basic application – Scripting delimiters • <? php ?> • Must enclose all script code – Variables preceded by $ symbol • Case-sensitive – End statements with semicolon – Comments • // for single line • /* */ for multiline – Filenames end with .php by convention2003 Prentice Hall, Inc. All rights reserved.
  • 5. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 52 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Outline34 <!-- Fig. 26.1: first.php -->5 <!-- Our first PHP script --> first.php6 Scripting delimiters (1 of 1)7 <?php8 $name = "LunaTic"; // declaration9 ?> Declare variable $name1011 <html xmlns = "http://www.w3.org/1999/xhtml">12 <head>13 <title>A simple PHP document</title>Single-line comment14 </head>1516 <body style = "font-size: 2em">17 <p>18 <strong>1920 <!-- print variable name’s value -->21 Welcome to PHP, <?php print( "$name" ); ?>!22 </strong>23 </p>24 </body> Function print outputs the value of variable $name25 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 6. 6 26.2 PHP Fig. 26.1 Simple PHP program.2003 Prentice Hall, Inc. All rights reserved.
  • 7. 7 26.2 PHP • Variables – Can have different types at different times – Variable names inside strings replaced by their value – Type conversions • settype function • Type casting – Concatenation operator • . (period) • Combine strings2003 Prentice Hall, Inc. All rights reserved.
  • 8. 8 26.2 PHP Data type Description int, integer Whole numbers (i.e., numbers without a decimal point). float, double Real numbers (i.e., numbers containing a decimal point). string Text enclosed in either single () or double ("") quotes. bool, Boolean True or false. array Group of elements of the same type. object Group of associated data and methods. Resource An external data source. NULL No value. Fig. 26.2 PHP data types.2003 Prentice Hall, Inc. All rights reserved.
  • 9. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 92 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline34 <!-- Fig. 26.3: data.php -->5 <!-- Demonstration of PHP data types --> data.php6 (1 of 3)7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>PHP data types</title>10 </head>1112 <body>1314 <?php Assign a string to variable15 $testString16 // declare a string, double and integer17 $testString = "3.5 seconds";18 $testDouble = 79.2; Assign a double to variable $testDouble Assign an integer to variable19 $testInteger = 12; $testInteger20 ?>21 2003 Prentice Hall, Inc. All rights reserved.
  • 10. 22 <!-- print each variable’s value --> 10 <?php print( $testString ); ?> is a string.<br />23 Outline24 <?php print( $testDouble ); ?> is a double.<br />25 <?php print( $testInteger ); ?> is an integer.<br />26 data.php27 <br /> Print each variable’s (2 of 3) value28 Now, converting to other types:<br />29 <?php3031 // call function settype to convert variable32 // testString to different data types33 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 Call function settype print( "Converting back to a string results in to41 $testString <br /><brfunction settypetype of Call />" ); the data to convert42 variable $testString to a convert the data type of43 $data = "98.6 degrees"; double. variable $testString to an integer. Convert variable $testString back to a string 2003 Prentice Hall, Inc. All rights reserved.
  • 11. 44 11 // use type casting to cast variables to a45 Outline46 // different type47 print ( "Now using type casting instead: <br />48 As a string - " . ( string ) $data . data.php49 "<br />As a double - " . (double ) $data . (3 of 3)50 "<br />As an integer - " . ( integer ) $data );51 ?> Use type casting to cast variable52 </body> $data to different types53 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 12. 12 26.2 PHP Fig. 26.3 Type conversion.2003 Prentice Hall, Inc. All rights reserved.
  • 13. 13 26.2 PHP • Arithmetic operators – Assignment operators • Syntactical shortcuts • Before being assigned values, variables have value undef • Constants – Named values – define function2003 Prentice Hall, Inc. All rights reserved.
  • 14. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 142 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline34 <!-- Fig. 26.4: operators.php -->5 <!-- Demonstration of operators --> operators.php6 (1 of 3)7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Using arithmetic operators</title>10 </head>1112 <body>13 <?php14 $a = 5; Define constant VALUE.15 print( "The value of variable a is $a <br />" );1617 // define constant VALUE Add constant VALUE to variable $a.18 define( "VALUE", 5 );1920 // add constant VALUE to variable $a21 $a = $a + VALUE;22 print( "Variable a after adding constant VALUE23 is $a <br />" );24 2003 Prentice Hall, Inc. All rights reserved.
  • 15. 25 // multiply variable $a by 2 15 $a *= 2;26 Multiply variable $a by two using the Outline27 print( "Multiplying variable a by 2 yields $a <br />" ); multiplication assignment operator *=.2829 // test if variable $a is less than 50 operators.php Test than 50 variable $a is less than 50 Print if variable $a is lesswhether .30 if ( $a < 50 ) (2 of 3)31 print( "Variable a is less than 50 <br />" );3233 // add 40 to variable $a Add 40 to variable $a using the addition assignment34 $a += 40; operator +=.35 print( "Variable a after adding 40 is $a <br />" );3637 // test if variable $a is 50 or less38 if ( $a < 51 )39 print( "Variable a is still 50 or less<br />" );4041 // test if variable $a is between 50 and 100, inclusive42 elseif ( $a < 101 )43 print( "Variable a is now between 50 and 100,44 inclusive<br />" );45 else46 print( "Variable a is now greater than 10047 <br />" );48 2003 Prentice Hall, Inc. All rights reserved.
  • 16. 49 // print an uninitialized variable 1650 print( "Using a variable before initializing: Outline51 $nothing <br />" );5253 // add constant VALUE to an uninitialized variable operators.php54 $test = $num + VALUE; (3 of 3)55 print( "An uninitialized variable plus constant56 VALUE yields $test <br />" );57 Print an uninitializedVALUE to ($nothing). Add constant variable an uninitialized58 // add a string to an integer variable.59 $str = "3 dollars";60 $a += $str;61 print( "Adding a string to variable a yields $a62 <br />" );63 ?>64 </body> Add a string to an integer.65 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 17. 17 26.2 PHP Fig. 26.4 Using PHP’s arithmetic operators.2003 Prentice Hall, Inc. All rights reserved.
  • 18. 18 26.2 PHP • Keywords – Reserved for language features – if…elseif…else • Arrays – Group of related data • Elements – Name plus braces and index • Indices start at zero – count function – array function2003 Prentice Hall, Inc. All rights reserved.
  • 19. 19 26.2 PHP • Arrays, cont. – Built-in iterators • Maintain pointer to element currently referenced • reset • key • next • foreach loops2003 Prentice Hall, Inc. All rights reserved.
  • 20. 20 26.2 PHP PHP keywords and do for include require true break else foreach list return var case elseif function new static virtual class extends global not switch xor continue false if or this while default Fig. 26.5 PHP keywords.2003 Prentice Hall, Inc. All rights reserved.
  • 21. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 212 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline34 <!-- Fig. 26.6: arrays.php -->5 <!-- Array manipulation --> arrays.php6 (1 of 3)7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Array manipulation</title>10 </head>1112 <body>13 <?php Create the array $first by assigning a value14 to an array element.15 // create array first16 print( "<strong>Creating the first array</strong>17 <br />" );18 $first[ 0 ] = "zero";19 $first[ 1 ] = Assign "one"; a value to the array, omitting the index.20 $first[ 2 ] = Appends a Use a for loop to print outthe array. "two"; new element to the end of each element’s index and value.21 $first[] = "three"; Function count returns the total number of elements in the22 array.23 // print each element’s index and value24 for ( $i = 0; $i < count( $first ); $i++ )25 print( "Element $i is $first[$i] <br />" ); 2003 Prentice Hall, Inc. All rights reserved.
  • 22. 26 22 print( "<br /><strong>Creating the second array27 Outline Call function array to create an array that contains28 </strong><br />" );29 the arguments passed to it. Store the array in variable30 // call function $second array to create array second . arrays.php31 $second = array( "zero", "one", "two", "three" ); (2 of 3)32 for ( $i = 0; $i < count( $second ); $i++ )33 print( "Element $i is $second[$i] <br />" );3435 print( "<br /><strong>Creating the third array36 </strong><br />" );3738 // assign values to non-numerical indices39 $third[ "ArtTic" ] = 21; Assign values to non-numerical indices40 $third[ "LunaTic" ] = 18; in array $third.41 $third[ "GalAnt" ] = 23; Function reset sets the internal pointer to the42 first element of the array.43 // iterate through the array elements and print each44 // element’s name and value45 for ( reset( $third ); $element = key( $third );46 next( $third ) )47 print( "$element is $third[$element] <br />" );48 Function key returns the index of the element which the internal pointer references. Function next moves the internal pointer to the next element. 2003 Prentice Hall, Inc. All rights reserved.
  • 23. 49 print( "<br /><strong>Creating the fourth array 23 </strong><br />" );50 Outline5152 // call function array to create array fourth using53 // string indices arrays.php54 $fourth = array( (3 of 3)55 "January" => "first", "February" => "second",56 "March" => "third", "April" => "fourth",57 "May" => "fifth", Operator =>=> used in function array to assign each "June" is "sixth",58 "July" => "seventh", "August" string index. The value to the left of the element a => "eighth",59 "September" => "ninth", operator is the array index, and the value to the right is "October" => "tenth",60 "November" => the element’s value. "eleventh","December" => "twelfth"61 );6263 // print each element’s name and value64 foreach ( $fourth as $element => $value )65 print( "$element is the $value month <br />" );66 ?>67 </body>68 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 24. 24 26.2 PHP Fig. 26.6 Array manipulation.2003 Prentice Hall, Inc. All rights reserved.
  • 25. 25 26.3 String Processing and Regular Expressions • String processing – Equality and comparison two important operations – strcmp function • Returns –1 if string 1 < string 2 • Returns 0 if string 1 = string 2 • Returns 1 if string 1 > string 2 – Relational operators2003 Prentice Hall, Inc. All rights reserved.
  • 26. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 262 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline34 <!-- Fig. 26.7: compare.php -->5 <!-- String Comparison --> compare.php6 (1 of 2)7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>String Comparison</title>10 </head>1112 <body>13 <?php Use a for loop to iterate through each array element.1415 // create array fruits16 $fruits = array( "apple", "orange", "banana" ); Function strcmp compares two strings. If the first string17 alphabetically precedes the second, then –1 is returned. If18 // iterate through each array element the strings are equal, 0 is returned. If the first string19 for ( $i = 0; $i < count( $fruits ); $i++ ) { alphabetically follows the second, then 1 is returned.2021 // call function strcmp to compare the array element22 // to string "banana"23 if ( strcmp( $fruits[ $i ], "banana" ) < 0 )24 print( $fruits[ $i ]." is less than banana " ); 2003 Prentice Hall, Inc. All rights reserved.
  • 27. 25 elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 ) 27 print( $fruits[ $i ].26 Outline27 " is greater than banana " );28 else29 print( $fruits[ $i ]." is Use relational operators equal to banana " ); to compare each array compare.php30 element to string “apple”. (2 of 2)31 // use relational operators to compare each element32 // to string "apple"33 if ( $fruits[ $i ] < "apple" )34 print( "and less than apple! <br />" );35 elseif ( $fruits[ $i ] > "apple" )36 print( "and greater than apple! <br />" );37 elseif ( $fruits[ $i ] == "apple" )38 print( "and equal to apple! <br />" );3940 }41 ?>42 </body>43 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 28. 28 26.3 String Processing and Regular Expressions Fig. 26.7 Using the string comparison operators.2003 Prentice Hall, Inc. All rights reserved.
  • 29. 29 26.3 String Processing and Regular Expressions • Regular expressions – Pattern matching templates – ereg function • POSIX – preg_match function • Perl – ereg_replace function • Building regular expressions – Metacharacters • $, ., ^ – Brackets [ ]2003 Prentice Hall, Inc. All rights reserved.
  • 30. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 302 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline34 <!-- Fig. 26.8: expression.php -->5 <!-- Using regular expressions --> expression.php6 (1 of 3)7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Regular expressions</title>10 </head>1112 <body>13 <?php Function ereg searches for the literal14 $search = "Now is the characters Now inside variable $search. time";15 print( "Test string is: $search<br /><br />" );1617 // call function ereg to search for pattern Now18 // in variable search19 if ( ereg( "Now", $search ) )20 print( "String Now was found.<br />" );21 2003 Prentice Hall, Inc. All rights reserved.
  • 31. 22 // search for pattern Now in the beginning of 31 // the string23 Outline24 if ( ereg( "^Now", $search ) ) The dollar sign special character ($) search for the25 print( "String Now found at beginning pattern Now (^) matches the The caret special character at the end of the string.26 of the line.<br />" ); expression.php27 beginning of a string. Function ereg searches the (2 of 3)28 // beginning ofthe end of for pattern Now . search for pattern Now at the string the string29 if ( ereg( "Now$", $search ) )30 print( "String Now was found at the end31 of the line.<br />" );3233 // search for any word ending in ow34 if ( ereg( "[[:<:]]([a-zA-Z]*ow)[[:>:]]", $search,35 $match ) )36 print( "Word found ending in ow: " .37 $match[ 1 ] . "<br />" );38 The special bracket parentheses, [a-zA-Z]*ow The expression inside the expressions [[:<:]] and ,39 // search for any words beginning with t Placing a word in the in ow. The quantifier * matches anypatternending beginning and end of a [[:>:]] match parentheses stores the matched40 print( "Words beginning with t found: ");41 word, preceding pattern 0 or more times. matches in the array that is specified in the third argument string therespectively. to function ereg.42 while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]",43 $search, $match ) ) {44 print( $match[ 1 ] . " " ); The pattern used in this example,45 [[:<:]](t[[:alpha:]]+)[[:>:]], matches any The while word is used to find each occurrence of a loop beginning with the Function eregi is used to specify case character t followed by one or insensitive string beginning with t. word in themore characters. Character class [[:alpha:]] pattern matches. recognizes any alphabetic character. 2003 Prentice Hall, Inc. All rights reserved.
  • 32. 46 // remove the first occurrence of a word beginning 32 // with t to find other instances in the string47 Outline48 $search = ereg_replace( $match[ 1 ], "", $search );49 }50 expression.php After printing a match of a word beginning with t, function51 print( "<br />" ); ereg_replace is called to remove the word from the of 3) (3 string.52 ?> This is necessary be because to find multiple instances of a53 </body> given pattern, the first matched instance must first be removed.54 </html> Function ereg_replace takes three arguments: the pattern to match, a string to replace the matched string and the string to search. 2003 Prentice Hall, Inc. All rights reserved.
  • 33. 33 26.3 String Processing and Regular Expressions Fig. 26.8 Regular expressions in PHP.2003 Prentice Hall, Inc. All rights reserved.
  • 34. 34 26.3 String Processing and Regular Expressions Quantifier Matches {n} Exactly n times. {m,n} Between m and n times inclusive. {n,} n or more times. + One or more times (same as {1,}). * Zero or more times (same as {0,}). ? Zero or one time (same as {0,1}). Fig. 26.9 Some PHP quantifiers.2003 Prentice Hall, Inc. All rights reserved.
  • 35. 35 26.3 String Processing and Regular Expressions Character class Description alnum Alphanumeric characters (i.e., letters [a-zA-Z] or digits [0-9]). alpha Word characters (i.e., letters [a-zA-Z]). digit Digits. space Whitespace. lower Lowercase letters. upper Uppercase letters. Fig. 26.10 Some PHP character classes.2003 Prentice Hall, Inc. All rights reserved.
  • 36. 36 26.4 Viewing Client/Server Environment Variables • Environment variables – Provide information about execution environment • Type of Web browser • Type of server • Details of HTTP connection – Stored as array in PHP • $_ENV2003 Prentice Hall, Inc. All rights reserved.
  • 37. 37 26.4 Viewing Client/Server Environment Variables Variable name Description $_SERVER Data about the currently running server. $_ENV Data about the client’s environment. $_GET Data posted to the server by the get method. $_POST Data posted to the server by the post method. $_COOKIE Data contained in cookies on the client’s computer. $GLOBALS Array containing all global variables. Fig. 26.11 Some useful global arrays.2003 Prentice Hall, Inc. All rights reserved.
  • 38. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 382 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline34 <!-- Fig. 26.11: env.php -->5 <!-- Program to display environment variables --> env.php6 (1 of 1)7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Environment Variables</title>10 </head>1112 <body>13 <table border = "0" cellpadding = "2" cellspacing = "0"14 width = "100%">15 <?php1617 // print the key and value for each element18 // in the $_ENV array19 foreach ( $_ENV as $key => $value )20 print( "<tr><td bgcolor = "#11bbff">21 The foreach loop <strong>$key</strong></td> is used to print out the keys and22 <td>$value</td></tr>"each element in the $_ENV array. values for );23 ?> PHP stores environment variables and their values in24 </table> the $_ENV array.25 </body>26 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 39. 39 26.4 Viewing Client/Server Environment Variables Fig. 26.12 Displaying environment variables.2003 Prentice Hall, Inc. All rights reserved.
  • 40. 40 26.5 Form Processing and Business Logic • Form processing – action property • Where to send form data – method property • post – Each element has unique name2003 Prentice Hall, Inc. All rights reserved.
  • 41. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 412 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline34 <!-- Fig. 26.13: form.html -->5 <!-- Form for use with the form.php program --> form.html6 (1 of 4)7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Sample form to take user input in XHTML</title>10 </head>1112 <body>13 The action attribute of the form element14 <h1>This is indicates that when the user clicks Register, the a sample registration form.</h1>15 Please fill in all fields and click Register. posted to form.php. form data will be1617 <!-- post form data to form.php -->18 <form method = "post" action = "form.php">19 <img src = "images/user.gif" alt = "User" /><br />20 <span style = "color: blue">21 Please fill out the fields below.<br />22 </span>23 2003 Prentice Hall, Inc. All rights reserved.
  • 42. 24 <!-- create four text boxes for user input --> 42 <img src = "images/fname.gif" alt = "First Name" />25 A unique name (e.g., email) is assigned to each Outline <input type = "text" name = "fname" /><br />26 of the form’s input fields. When Register is27 clicked, each field’s name and value are sent to28 <img src = "images/lname.gif" alt = "Last Name" /> the Web server. form.html29 <input type = "text" name = "lname" /><br /> (2 of 4)3031 <img src = "images/email.gif" alt = "Email" />32 <input type = "text" name = "email" /><br />3334 <img src = "images/phone.gif" alt = "Phone" />35 <input type = "text" name = "phone" /><br />3637 <span style = "font-size: 10pt">38 Must be in the form (555)555-5555</span>39 <br /><br />4041 <img src = "images/downloads.gif"42 alt = "Publications" /><br />4344 <span style = "color: blue">45 Which book would you like information about?46 </span><br />47 2003 Prentice Hall, Inc. All rights reserved.
  • 43. 48 <!-- create drop-down list containing book names --> 43 <select name = "book">49 Outline50 <option>Internet and WWW How to Program 3e</option>51 <option>C++ How to Program 4e</option>52 <option>Java How to Program 5e</option> form.html53 <option>XML How to Program 1e</option> (3 of 4)54 </select>55 <br /><br />5657 <img src = "images/os.gif" alt = "Operating System" />58 <br /><span style = "color: blue">59 Which operating system are you currently using?60 <br /></span>6162 <!-- create five radio buttons -->63 <input type = "radio" name = "os" value = "Windows XP"64 checked = "checked" />65 Windows XP6667 <input type = "radio" name = "os" value =68 "Windows 2000" />69 Windows 20007071 <input type = "radio" name = "os" value =72 "Windows 98" />73 Windows 98<br /> 2003 Prentice Hall, Inc. All rights reserved.
  • 44. 74 44 <input type = "radio" name = "os" value = "Linux" />75 Outline76 Linux7778 <input type = "radio" name = "os" value = "Other" /> form.html79 Other<br /> (4 of 4)8081 <!-- create a submit button -->82 <input type = "submit" value = "Register" />83 </form>8485 </body>86 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 45. 45 26.5 Form Processing and Business Logic Fig. 26.13 XHTML form for gathering user input.2003 Prentice Hall, Inc. All rights reserved.
  • 46. 46 26.5 Form Processing and Business Logic • Business logic – Confirm that valid information was entered – extract function • Creates variables corresponding to each key-value pair in array • Easily retrieve all values sent to PHP page – Regular expressions very helpful – Do checks on client side where possible • JavaScript • Conserves server resources • Ending a script – die function • Remember to close all HTML tags2003 Prentice Hall, Inc. All rights reserved.
  • 47. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 472 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline34 <!-- Fig. 26.14: form.php -->5 <!-- Read information sent from form.html --> form.php6 (1 of 4)7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Form Validation</title>10 </head>1112 <body style = "font-family: arial,sans-serif"> Function ereg is called to determine whether the13 The parentheses in the expression must be14 <?php phone number entered by the user is valid. three digits ([0-9]{3}), a the opening followed by The expression ( matches closing15 extract( $_POST ); parenthesis, parentheses ofliteral hyphen and three digits, a a phone number.16 four additional digits.17 // determine whether phone number is valid and print18 // an error message if not19 if ( !ereg( "^([0-9]{3})[0-9]{3}-[0-9]{4}$",20 $phone ) ){21 We access the phone field’s value from form.html by using variable $phone. 2003 Prentice Hall, Inc. All rights reserved.
  • 48. 22 print( "<p><span style = "color: red; 48 font-size: 2em">23 Outline24 INVALID PHONE NUMBER</span><br />25 A valid phone number must be in the form26 <strong>(555)555-5555</strong><br /> form.php27 <span style = "color: blue"> (2 of 4)28 Click the Back button, enter a valid phone Function die terminates script execution29 number and resubmit.<br /><br />30 Thank You.</span></p></body></html>" );3132 die(); // terminate script execution33 }34 ?>3536 <p>Hi37 <span style = "color: blue">38 <strong>39 <?php print( "$fname" ); ?>40 </strong>41 </span>.42 Thank you for completing the survey.<br />43 2003 Prentice Hall, Inc. All rights reserved.
  • 49. 44 You have been added to the 49 <span style = "color: blue">45 Outline46 <strong>47 <?php print( "$book " ); ?>48 </strong> form.php49 </span> (3 of 4)50 mailing list.51 </p>52 <strong>The following information has been saved53 in our database:</strong><br />5455 <table border = "0" cellpadding = "0" cellspacing = "10">56 <tr>57 <td bgcolor = "#ffffaa">Name </td>58 <td bgcolor = "#ffffbb">Email</td>59 <td bgcolor = "#ffffcc">Phone</td>60 <td bgcolor = "#ffffdd">OS</td>61 </tr>6263 <tr>64 <?php65 2003 Prentice Hall, Inc. All rights reserved.
  • 50. 66 // print each form field’s value 50 print( "<td>$fname $lname</td>67 Outline68 <td>$email</td>69 <td>$phone</td>70 <td>$os</td>" ); form.php71 ?> (4 of 4)72 </tr>73 </table>7475 <br /><br /><br />76 <div style = "font-size: 10pt; text-align: center">77 This is only a sample form.78 You have not been added to a mailing list.79 </div>80 </body>81 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 51. 51 26.5 Form Processing and Business Logic Fig. 26.14 Obtaining user input through forms.2003 Prentice Hall, Inc. All rights reserved.
  • 52. 52 26.6 Verifying a Username and Password • Private website – Only accessible to certain individuals – Encrypt username and password data when sending, storing and retrieving for increased security • Implementing password checking – Login information stored in file • fopen function • Read, write, append modes – Store data using fputs • n newline character – Close files when done • fclose function2003 Prentice Hall, Inc. All rights reserved.
  • 53. 53 26.6 Verifying a Username and Password • Implementing password checking, cont. – Trim newline character • chop function – Split string into substrings given a certain delimiter • split function – If username/password match list, allow access2003 Prentice Hall, Inc. All rights reserved.
  • 54. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 542 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline34 <!-- Fig. 26.15: password.html -->5 <!-- XHTML form sent to password.php for verification --> password.html6 (1 of 4)7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Verifying a username and a password.</title>1011 <style type = "text/css">12 td { background-color: #DDDDDD }13 </style>14 </head>1516 <body style = "font-family: arial">17 <p style = "font-size: 13pt">18 Type in your username and password below.19 <br />20 <span style = "color: #0000FF; font-size: 10pt;21 font-weight: bold">22 Note that password will be sent as plain text23 </span>24 </p>25 2003 Prentice Hall, Inc. All rights reserved.
  • 55. 26 <!-- post form data to password.php --> 55 <form action = "password.php" method = "post">27 Outline28 <br />29 Form data is posted to password.php.30 <table border = "0" cellspacing = "0" password.html31 style = "height: 90px; width: 123px; (2 of 4)32 font-size: 10pt" cellpadding = "0">3334 <tr>35 <td colspan = "3">36 <strong>Username:</strong>37 </td>38 </tr>3940 <tr>41 <td colspan = "3">42 <input size = "40" name = "USERNAME"43 style = "height: 22px; width: 115px" />44 </td>45 </tr>46 2003 Prentice Hall, Inc. All rights reserved.
  • 56. 47 <tr> 56 <td colspan = "3">48 Outline49 <strong>Password:</strong>50 </td>51 </tr> password.html52 (3 of 4)53 <tr>54 <td colspan = "3">55 <input size = "40" name = "PASSWORD"56 style = "height: 22px; width: 115px"57 type = "password" />58 <br/></td>59 </tr>6061 <tr>62 <td colspan = "1">63 <input type = "submit" name = "Enter"64 value = "Enter" style = "height: 23px;65 width: 47px" />66 </td>67 <td colspan = "2">68 <input type = "submit" name = "NewUser"69 value = "New User"70 style = "height: 23px" />71 </td> 2003 Prentice Hall, Inc. All rights reserved.
  • 57. 72 </tr> 57 </table>73 Outline74 </form>75 </body>76 </html> password.html (4 of 4) 2003 Prentice Hall, Inc. All rights reserved.
  • 58. 58 26.6 Verifying a Username and Password Fig. 26.15 XHTML form for obtaining a username and password.2003 Prentice Hall, Inc. All rights reserved.
  • 59. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 592 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline34 <!-- Fig. 26.16: password.php -->5 <!-- Searching a database for usernames and passwords. --> password.php6 (1 of 7)7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head> Variable names, when preceded by the logical9 <?php negation operator (!), return true if they are empty10 extract( $_POST ); or set to 0. This checks if a user has submitted a form11 without specifying a username or password.12 // check if user has left USERNAME or PASSWORD field blank13 if ( !$USERNAME || !$PASSWORD ) { Function fieldsBlank is called if the user has14 fieldsBlank(); Function isset tests whether the notify the user submitted an incomplete form to user has15 die(); pressed form fields must be completed. that a that all the New User button, indicating16 } new user must be added.1718 // check if the New User button was clicked new To add a user, we open the file19 if ( isset( $NewUser ) ) { password.txt in append mode and assign the20 file handle that is returned to variable $file.21 // open password.txt for writing using append mode22 if ( !( $file = fopen( "password.txt",23 "a" ) ) ) {24 2003 Prentice Hall, Inc. All rights reserved.
  • 60. 25 // print error message and terminate script 60 // execution if file cannot be opened26 Outline27 print( "<title>Error</title></head><body>28 Could not open password file29 </body></html>" ); password.php30 die(); Print an error message and terminate script execution (2 of 7)31 } if the file cannot be opened.3233 // write username and password to file and34 // call function userAdded35 fputs( $file, "$USERNAME,$PASSWORDn" );36 userAdded( $USERNAME );37 }38 else { Function userAdded is called to print a message to the Function fputs writes the name and password to the39 user to indicate that the username and password were text file..40 // if a new user added to the file. is not being added, open file41 // for reading42 if ( !( $file = fopen( "password.txt",43 "r" ) ) ) {44 print( "<title>Error</title></head>45 <body>Could not open password file46 </body></html>" );47 die();48 }49 2003 Prentice Hall, Inc. All rights reserved.
  • 61. 50 $userVerified = 0; 6151 Outline52 // read each line in file and check username Before entering the while loop, variable53 // and password Function fgets reads a lineset to 0. text file. $userVerified is from the54 while ( !feof( $file result !$userVerified variable $line. The ) && is assigned to ) { password.php55 (3 of 7)56 // read line from file57 The while loop executes as long as the there are more $line = fgets( Function chop $file, 255 ); removes the newline character58 from the and variable $userVerified is lines in the file to read end of the line. Function split still 0 or empty. is called to separate the string at the59 // remove newline character from end of line specified delimiter (in this case, a comma). The60 $line = chop( $line ); resulting array usernamein array $fielduser is tested The is stored entered by the .61 against the one returned in the text file (stored62 // split username and password in the first element of the array). If they match,63 $field = split( ",", $line, 2 ); variable $userVerified is set to 1.6465 // verify username66 if ( $USERNAME == $field[ 0 ] ) {67 $userVerified = 1;6869 // call function checkPassword to If function verify checkPassword returns true, function70 // user’s password accessGranted is called to notify the client that71 permission if ( checkPassword( $PASSWORD, $field ) has been granted. Otherwise, function72 == true ) wrongPassword is called.73 accessGranted( $USERNAME );74 else Function checkPassword is called to verify the75 wrongPassword(); user’s password. Variable $PASSWORD and array $field are passed to the function. 2003 Prentice Hall, Inc. All rights reserved.
  • 62. 76 } 62 }77 Outline78 If variable $userVerified has not been set to a79 // close text file than the while accessDenied is value otherAfter 0, function loop has executed, function80 fclose( $file ); fclose is called to close has been called to notify the client that access the file. password.php81 denied. (4 of 7)82 // call function accessDenied if username has83 // not been verified Function checkPassword compares the user’s84 if ( !$userVerified ) password to the password in the file. If they match,85 accessDenied(); true is returned, whereas false is returned if they86 } do not.8788 // verify user password and return a boolean89 function checkPassword( $userpassword, $filedata )90 {91 if ( $userpassword == $filedata[ 1 ] )92 return true;93 else94 return false;95 }96 2003 Prentice Hall, Inc. All rights reserved.
  • 63. 97 // print a message indicating the user has been added 63 function userAdded( $name )98 Outline99 {100 print( "<title>Thank You</title></head>101 <body style = "font-family: userAdded Function arial; prints a message to the password.php102 font-size: 1em; client indicating that the user has been added. color: blue"> (5 of 7)103 <strong>You have been added104 to the user list, $name. Function accessGranted prints a105 <br />Enjoy the message to the client indicating that site.</strong>" );106 } permission has been granted.107108 // print a message indicating permission109 // has been granted110 function accessGranted( $name )111 {112 print( "<title>Thank You</title></head>113 <body style = "font-family: arial;114 font-size: 1em; color: blue">115 <strong>Permission has been116 granted, $name. <br />117 Enjoy the site.</strong>" );118 }119 2003 Prentice Hall, Inc. All rights reserved.
  • 64. 120 // print a message indicating password is invalid 64 function wrongPassword()121 Outline122 { Function wrongPassword prints a message to the123 print( "<title>Access Denied</title></head> client indicating that the password is invalid.124 <body style = "font-family: arial; password.php125 font-size: 1em; color: red"> (6 of 7)126 <strong>You entered an invalid127 password.<br />Access has128 been denied.</strong>" );129 }130131 // print a message indicating access has been denied132 function accessDenied()133 {134 print( "<title>Access Denied</title></head>135 <body style = "font-family: arial;136 font-size: 1em; color: red">137 <strong>138 You were denied access to this server.139 <br /></strong>" ); Function accessDenied prints a message to the140 } client indicating that access has been denied.141 2003 Prentice Hall, Inc. All rights reserved.
  • 65. 142 // print a message indicating that fields 65 // have been left blank143 Function fieldsBlank prints a message to Outline the144 function fieldsBlank() client indicating that all form fields have not been145 { completed.146 print( "<title>Access Denied</title></head> password.php147 <body style = "font-family: arial; (7 of 7)148 font-size: 1em; color: red">149 <strong>150 Please fill in all form fields.151 <br /></strong>" );152 }153 ?>154 </body>155 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 66. 66 26.6 Verifying a Username and Password Fig. 26.16 Verifying a username and password.2003 Prentice Hall, Inc. All rights reserved.
  • 67. 1 account1,password1 672 account2,password2 Outline3 account3,password34 account4,password45 account5,password5 password.txt6 account6,password6 (1 of 1)7 account7,password78 account8,password89 account9,password910 account10,password10 2003 Prentice Hall, Inc. All rights reserved.
  • 68. 68 26.7 Connecting to a Database • Databases – Store and maintain data – MySQL is a free database product – PHP supports many database operations • Access databases from Web pages2003 Prentice Hall, Inc. All rights reserved.
  • 69. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 69 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">2 Outline34 <!-- Fig. 26.18: data.html -->5 <!-- Querying a MySQL Database --> data.html6 (1 of 2)7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Sample Database Query</title>10 </head>1112 <body style = "background-color: #F0E68C">13 <h2 style = "font-family: arial color: blue">14 Querying a MySQL database.15 </h2>1617 <form method = "post" action = "database.php">18 <p>Select a field to display:1920 <!-- add a select box containing options -->21 <!-- for SELECT query --> 2003 Prentice Hall, Inc. All rights reserved.
  • 70. 22 <select name = "select"> 70 <option selected = "selected">*</option>23 Outline24 <option>ID</option>25 <option>Title</option> Select box containing options for a SELECT26 <option>Category</option> query. data.html27 <option>ISBN</option> (2 of 2)28 </select>29 </p>3031 <input type = "submit" value = "Send Query"32 style = "background-color: blue;33 color: yellow; font-weight: bold" />34 </form>35 </body>36 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 71. 71 26.7 Connecting to a Database Fig. 26.18 Form to query a MySQL database.2003 Prentice Hall, Inc. All rights reserved.
  • 72. 72 26.7 Connecting to a Database • Interacting with databases – SQL • Structured Query Language • Used to manipulate databases – Several useful functions • mysql_connect • mysql_select_db • mysql_query • mysql_error • mysql_fetch_row • mysql_close2003 Prentice Hall, Inc. All rights reserved.
  • 73. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 732 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline34 <!-- Fig. 26.19: database.php -->5 <!-- Program to query a database and --> database.php6 <!-- send results to the client. --> (1 of 3)78 <html xmlns = "http://www.w3.org/1999/xhtml">9 <head>10 <title>Search Results</title>11 </head>1213 <body style = "font-family: arial, sans-serif"14 style = "background-color: #F0E68C">15 <?php Build the select query and assign the16 string to variable $query.17 extract( $_POST ); Function mysql_connect returns a database18 handle which represents PHP’s connection to a19 // build SELECT query database. If this connection is not made, function20 $query = "SELECT " . $select . " FROM Books"; die is called to terminate script execution.2122 // Connect to MySQL23 if ( !( $database = mysql_connect( "localhost",24 "httpd", "" ) ) )25 die( "Could not connect to database" ); 2003 Prentice Hall, Inc. All rights reserved.
  • 74. 26 7427 // open Products database Outline28 if ( !mysql_select_db( "Products", $database )mysql_query Function ) returns an object29 containing the result set of the query, which die( "Could not open Products database" );30 we assign to variable $result. database.php31 // query Products database (2 of 3)32 if ( !( $result = mysql_query( $query, $database ) ) ) { Function mysql_select_db is called to specify the33 print( "Could not execute query! <br />" ); database to be queried.34 die( mysql_error() );35 }36 ?>3738 <h3 style = "color: blue">39 Search Results</h3>4041 <table border = "1" cellpadding = "3" cellspacing = "2"42 style = "background-color: #ADD8E6">4344 <?php The for loop iterates through each45 record in the result set while46 // fetch each record in result setconstructing an XHTML table from47 for ( $counter = 0; the results. Variable $counter is48 $row = mysql_fetch_row( $result incremented by one for each row );49 $counter++ ){ retrieved. Function mysql_fetch_row returns an50 array containing the elements of each row in the result set of our query ($result). 2003 Prentice Hall, Inc. All rights reserved.
  • 75. 51 // build table to display results 7552 print( "<tr>" ); Outline5354 foreach ( $row as $key => $value )55 print( "<td>$value</td>" ); database.php56 (3 of 3)57 print( "</tr>" ); The foreach loop iterates through the58 } array containing the elements of each row59 and prints out each element in an60 mysql_close( $databaseThe total number of results are printed to the ); individual table cell.61 ?> client.6263 </table>6465 <br />Your search yielded <strong>66 <?php print( "$counter" ) ?> results.<br /><br /></strong>6768 <h5>Please email comments to69 <a href = "mailto:deitel@deitel.com">70 Deitel and Associates, Inc.71 </a>72 </h5>7374 </body>75 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 76. 76 26.7 Connecting to a Database Fig. 26.19 Querying a database and displaying the results.2003 Prentice Hall, Inc. All rights reserved.
  • 77. 77 26.8 Cookies • Cookies – Store information on client computer – Track preferences and other information – Stored as text files on hard drive – Never store sensitive information, such as credit card numbers, in a cookie • Security risk • Cookies and PHP – setcookie function • Name • Value • Expiration date2003 Prentice Hall, Inc. All rights reserved.
  • 78. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 782 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline34 <!-- Fig. 26.20: cookies.html -->5 <!-- Writing a Cookie --> cookies.html6 (1 of 2)7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Writing a cookie to the client computer</title>10 </head>1112 <body style = "font-family: arial, sans-serif;13 background-color: #99CCFF">1415 <h2>Click Write Cookie to save your cookie data.</h2>16 2003 Prentice Hall, Inc. All rights reserved.
  • 79. 17 <form method = "post" action = "cookies.php" 79 style = "font-size: 10pt">18 Outline19 <strong>Name:</strong><br /> Form data is posted to cookies.php.20 <input type = "text" name = "NAME" /><br />21 cookies.html22 <strong>Height:</strong><br /> (2 of 2)23 <input type = "text" name = "HEIGHT" /><br />2425 <strong>Favorite Color:</strong><br />26 <input type = "text" name = "COLOR" /><br />2728 <input type = "submit" value = "Write Cookie"29 style = "background-color: #F0E86C; color: navy;30 font-weight: bold" /></p>31 </form>32 </body>33 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 80. 80 26.8 Cookies Fig. 26.20 Gathering data to be written as a cookie.2003 Prentice Hall, Inc. All rights reserved.
  • 81. 1 <?php 812 // Fig. 26.21: cookies.php Outline3 // Program to write a cookie to a clients machine45 extract( $_POST ); cookies.php6 // write each form field’s value to a cookie and set the (1 of 2)7 // cookie’s expiration date8 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 ?> Function setcookie takes the name of the12 cookie to be set as the first argument,13 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" the value to be stored in the followed by14 cookie. The optional third argument specifies "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">15 the expiration date of the cookie.16 <html xmlns = "http://www.w3.org/1999/xhtml">17 <head>18 <title>Cookie Saved</title>19 </head>2021 <body style = "font-family: arial, sans-serif">22 <p>The cookie has been set with the following data:</p>23 2003 Prentice Hall, Inc. All rights reserved.
  • 82. 24 <!-- print each form field’s value --> 8225 Each <br /><span style = "color: blue">Name:</span> form field’s value is printed to Outline26 <?php print( $NAME ) ?><br /> confirm the data that has been set as a27 cookie with the user.28 <span style = "color: blue">Height:</span> cookies.php29 <?php print( $HEIGHT ) ?><br /> (2 of 2)3031 <span style = "color: blue">Favorite Color:</span>3233 <span style = "color: <?php print( "$COLOR">$COLOR" ) ?>34 </span><br />35 <p>Click <a href = "readCookies.php">here</a>36 to read the saved cookie.</p>37 </body>38 </html> Hyperlink to readCookies.php. 2003 Prentice Hall, Inc. All rights reserved.
  • 83. 83 26.8 Cookies Fig. 26.21 Writing a cookie to the client.2003 Prentice Hall, Inc. All rights reserved.
  • 84. 84 26.8 Cookies • Reading cookies – $_COOKIE environment variable • Array – foreach loop to access each element • Split into key and value2003 Prentice Hall, Inc. All rights reserved.
  • 85. 85 26.8 Cookies • Cookie storage – Internet Explorer • Stores cookies in Cookies directory • Text file2003 Prentice Hall, Inc. All rights reserved.
  • 86. 86 26.8 Cookies Fig. 26.22 Cookies directory before a cookie is written. Fig. 26.23 Cookies directory after a cookie is written.2003 Prentice Hall, Inc. All rights reserved.
  • 87. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 872 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline34 <!-- Fig. 26.24: readCookies.php -->5 <!-- Program to read cookies from the clients computer --> readCookies.php6 (1 of 2)7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head><title>Read Cookies</title></head>910 <body style = "font-family: arial, sans-serif">1112 <p>13 <strong>14 The following data is saved in a cookie on your15 computer.16 </strong>17 </p>18 2003 Prentice Hall, Inc. All rights reserved.
  • 88. 19 <table border = "5" cellspacing = "0" cellpadding = "10"> 88 <?php20 The foreach loop iterates through the $_COOKIE PHP creates array $_COOKIE which contains Outline21 array and prints the name and value of each cookie all cookie values indexed by their names.22 // iterate through array $_COOKIE and print in an XHTML table.23 // name and value of each cookie readCookies.php24 foreach ( $_COOKIE as $key => $value ) (2 of 2)25 print( "<tr>26 <td bgcolor="#F0E68C">$key</td>27 <td bgcolor="#FFA500">$value</td>28 </tr>" );29 ?>3031 </table>32 </body>33 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 89. 89 26.8 Cookies Fig. 26.24 Displaying the cookie’s content.2003 Prentice Hall, Inc. All rights reserved.
  • 90. 90 26.9 Dynamic Content in PHP • Dynamically alter XHTML content – Form’s action property set to same page that contains it – Perform different actions when page is loaded and form is submitted • isset variable – Check for errors • Write different XHTML when errors encountered – $$variable syntax • References variable whose name equals the value of $variable – If input is valid, make MySQL database calls2003 Prentice Hall, Inc. All rights reserved.
  • 91. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 912 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline34 <!-- Fig. 26.25: dynamicForm.php -->5 <!-- Form for use with the form.php program --> dynamicForm.php6 (1 of 9)7 <html xmlns = "http://www.w3.org/1999/xhtml">8 <head>9 <title>Sample form to take user input in XHTML</title>10 </head>1112 <body>13 <?php14 extract ( $_POST ); Build array of options for the form.15 $iserror = false;1617 // array of book titles18 $booklist = array( "Internet and WWW How to Program 3e",19 "C++ How to Program 4e",20 "Java How to Program 5e",21 "XML How to Program 1e" );22 2003 Prentice Hall, Inc. All rights reserved.
  • 92. 23 // array of possible operating systems 92 $systemlist = array( "Windows XP",24 Outline25 "Windows 2000",26 "Windows 98",27 "Linux", dynamicForm.php28 "Other"); (2 of 9)2930 // array of name and alt values for the text input fields31 $inputlist = array( "fname" => "First Name",32 "lname" => "Last Name", If the page is being loaded as a result of a form33 "email" => "Email", submission,errors or omissionsandform field Check for do error checking in then retrieve34 "phone" => "Phone" ); information from the database. input.3536 if ( isset ( $submit ) ) {37 if ( $fname == "" ) {38 $formerrors[ "fnameerror" ] = true;39 $iserror = true;40 }4142 if ( $lname == "" ) {43 $formerrors[ "lnameerror" ] = true;44 $iserror = true;45 }46 2003 Prentice Hall, Inc. All rights reserved.
  • 93. 47 if ( $email == "" ) { 93 $formerrors[ "emailerror" ] = true;48 Outline49 $iserror = true;50 }51 dynamicForm.php52 if ( !ereg( "^([0-9]{3})[0-9]{3}-[0-9]{4}$", $phone ) ) { (3 of 9)53 $formerrors[ "phoneerror" ] = true;54 $iserror = true;55 }56 If there were no errors, query the MySQL57 if ( !$iserror ) { database.5859 // build INSERT query60 $query = "INSERT INTO contacts " .61 "( LastName, FirstName, Email, Phone, Book, OS ) " .62 "VALUES ( $lname, $fname, $email, " .63 "" . quotemeta( $phone ) . ", $book, $os )";6465 // Connect to MySQL66 if ( !( $database = mysql_connect( "localhost",67 "httpd", "" ) ) )68 die( "Could not connect to database" );6970 // open MailingList database71 if ( !mysql_select_db( "MailingList", $database ) )72 die( "Could not open MailingList database" ); 2003 Prentice Hall, Inc. All rights reserved.
  • 94. 73 94 // execute query in MailingList database74 Outline75 if ( !( $result = mysql_query( $query, $database ) ) ) {76 print( "Could not execute query! <br />" );77 die( mysql_error() ); dynamicForm.php78 } (4 of 9)7980 print( "<p>Hi81 <span style = color: blue>82 <strong>$fname</strong></span>.83 Thank you for completing the survey.<br />8485 You have been added to the86 <span style = color: blue>87 <strong>$book</strong></span>88 mailing list.89 </p>90 <strong>The following information has been saved91 in our database:</strong><br />9293 <table border = 0 cellpadding = 0 cellspacing = 10>94 <tr>95 <td bgcolor = #ffffaa>Name</td>96 <td bgcolor = #ffffbb>Email</td>97 <td bgcolor = #ffffcc>Phone</td> 2003 Prentice Hall, Inc. All rights reserved.
  • 95. 98 <td bgcolor = #ffffdd>OS</td> 95 </tr>99 Outline100 <tr>101102 <!-- print each form field’s value --> dynamicForm.php103 <td>$fname $lname</td> (5 of 9)104 <td>$email</td>105 <td>$phone</td>106 <td>$os</td>107 </tr></table>108109 <br /><br /><br />110 <div style = font-size: 10pt; text-align: center>111 <div style = font-size : 18pt>112 <a href = formDatabase.php>113 Click here to view entire database.</a></div> Halt the script so the form-generation code114 This is only a sample form. does not execute.115 You have not been added to a mailing list.116 </div></body></html>" );117 die();118 }119 }120121 print( "<h1>This is a sample registration form.</h1>122 Please fill in all fields and click Register." ); 2003 Prentice Hall, Inc. All rights reserved.
  • 96. 123 96 if ( $iserror ) {124 Outline125 print( "<br /><span style = color : red>126 Fields with * need to be filled in properly.</span>" );127 } dynamicForm.php128 (6 of 9)129 print( "<!-- post form data to form.php -->130 <form method = post action = dynamicform.php>131 <img src = images/user.gif alt = User /><br />132 <span style = color: blue>133 Please fill out the fields below.<br />134 </span>135136 <!-- create four text boxes for user input -->" ); Fill in the forms using $$variable syntax.137 foreach ( $inputlist as $inputname => $inputalt ) {138 $inputtext = $inputvalues[ $inputname ];139140 print( "<img src = images/$inputname.gif If the form input contained errors, place a red141 alt = $inputalt /><input type = text asterisk (*) next to the text field.142 name = $inputname value = " . $$inputname . " />" );143144 if ( $formerrors[ ( $inputname )."error" ] == true )145 print( "<span style = color : red>*</span>" );146147 print( "<br />" );148 } 2003 Prentice Hall, Inc. All rights reserved.
  • 97. 149 97 print( "<span style = font-size : 10pt" );150 Outline151152 if ( $formerrors[ "phoneerror" ] )153 print( "; color : red" ); dynamicForm.php154 (7 of 9)155 print( ">Must be in the form (555)555-5555156 </span><br /><br />157158 <img src = images/downloads.gif159 alt = Publications /><br />160161 <span style = color: blue>162 Which book would you like information about?163 </span><br />164165 <!-- create drop-down list containing book names -->166 <select name = book>" );167 Make sure the correct book is selected in the168 foreach ( $booklist as $currbook ) { dropdown box.169 print( "<option" );170171 if ( ( $currbook == $book ) )172 print( " selected = true" );173 2003 Prentice Hall, Inc. All rights reserved.
  • 98. 174 print( ">$currbook</option>" ); 98 }175 Outline176177 print( "</select><br /><br />178 <img src = images/os.gif alt = Operating System /> dynamicForm.php179 <br /><span style = color: blue> (8 of 9)180 Which operating system are you currently using?181 <br /></span>182183 <!-- create five radio buttons -->" );184185 $counter = 0;186187 foreach ( $systemlist as $currsystem ) {188 Make sure the correct OS is checked in the print( "<input type = radio name = os189 value = checkbox. $currsystem" );190191 if ( $currsystem == $os ) print( "checked = checked" );192 if ( $iserror && $counter == 0 ) print( "checked = checked" );193194 print( " />$currsystem" );195196 if ( $counter == 2 ) print( "<br />" );197 $counter++;198 }199 2003 Prentice Hall, Inc. All rights reserved.
  • 99. 200 print( "<!-- create a submit button --> 99 <br />201 Outline202 <input type = submit name = submit value = Register />203 </form></body></html>" );204 ?> dynamicForm.php (9 of 9) 2003 Prentice Hall, Inc. All rights reserved.
  • 100. 100 26.9 Dynamic Content in PHP Fig. 26.25 Dynamic form using PHP.2003 Prentice Hall, Inc. All rights reserved.
  • 101. 101 26.9 Dynamic Content in PHP Fig. 26.25 Dynamic form using PHP.2003 Prentice Hall, Inc. All rights reserved.
  • 102. 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 1022 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Outline34 <!-- Fig. 26.26: formDatabase.php -->5 <!-- Program to query a database and --> formDatabase.php6 <!-- send results to the client. --> (1 of 3)78 <html xmlns = "http://www.w3.org/1999/xhtml">9 <head>10 <title>Search Results</title>11 </head>1213 <body style = "font-family: arial, sans-serif"14 style = "background-color: #F0E68C">15 <?php16 Build the query string.17 extract( $_POST );1819 // build SELECT query20 $query = "SELECT * FROM contacts";2122 // Connect to MySQL23 if ( !( $database = mysql_connect( "localhost",24 "httpd", "" ) ) )25 die( "Could not connect to database" ); 2003 Prentice Hall, Inc. All rights reserved.
  • 103. 26 103 // open MailingList database27 Outline28 if ( !mysql_select_db( "MailingList", $database ) )29 die( "Could not open MailingList database" );30 formDatabase.php31 // query MailingList database (2 of 3)32 if ( !( $result = mysql_query( $query, $database ) ) ) {33 print( "Could not execute query! <br />" );34 die( mysql_error() );35 }36 ?>3738 <h3 style = "color: blue">39 Mailing List Contacts</h3>4041 <table border = "1" cellpadding = "3" cellspacing = "2"42 style = "background-color: #ADD8E6">4344 <tr>45 <td>ID</td>46 <td>Last Name</td>47 <td>First Name</td>48 <td>E-mail Address</td>49 <td>Phone Number</td>50 <td>Book</td> 2003 Prentice Hall, Inc. All rights reserved.
  • 104. 51 <td>Operating System</td> 104 </tr>52 Outline53 <?php Retrieve each mailing list54 member record from the55 // fetch each record in resultdatabase. set formDatabase.php56 for ( $counter = 0; (3 of 3)57 $row = mysql_fetch_row( $result );58 $counter++ ){59 Dynamically create a table60 // build table to display results containing each mailing list61 print( "<tr>" ); member.6263 foreach ( $row as $key => $value )64 print( "<td>$value</td>" );6566 print( "</tr>" );67 }6869 mysql_close( $database );70 ?>7172 </table>7374 </body>75 </html> 2003 Prentice Hall, Inc. All rights reserved.
  • 105. 105 26.9 Dynamic Content in PHP Fig. 26.26 Displaying the MailingList database.2003 Prentice Hall, Inc. All rights reserved.
  • 106. 106 26.10 Operator Precedence Operator Type Associativity new constructor none [] subscript right to left ~ bitwise not right to left ! not ++ increment -- decrement - unary negative @ error control * multiplication left to right / division % modulus + addition left to right - subtraction . concatenation << bitwise shift left left to right >> bitwise shift right < less than none > greater than <= less than or equal >= greater than or equal == equal none != not equal === identical !== not identical Fig. 26.27 PHP operator precedence and associativity.2003 Prentice Hall, Inc. All rights reserved.
  • 107. 107 26.10 Operator Precedence Operator Type Associativity & bitwise AND left to right ^ bitwise XOR left to right | bitwise OR left to right && logical AND left to right || logical OR left to right = assignment 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. 26.27 PHP operator precedence and associativity.2003 Prentice Hall, Inc. All rights reserved.