5

Welcome to PHP, !

25 First.php Program Output Scripting delimiters Declare variable $name Single-line comment Function print outputs the value of variable $name"> 5

Welcome to PHP, !

25 First.php Program Output Scripting delimiters Declare variable $name Single-line comment Function print outputs the value of variable $name">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 29 - PHP Outline 29.1 Introduction 29.2 PHP

Similar presentations


Presentation on theme: "Chapter 29 - PHP Outline 29.1 Introduction 29.2 PHP"— Presentation transcript:

1 Chapter 29 - PHP Outline 29.1 Introduction 29.2 PHP
String Processing and Regular Expressions Viewing Client/Server Environment Variables Form Processing and Business Logic Verifying a Username and Password Connecting to a Database Cookies Operator Precedence Internet and World Wide Web Resources

2 First.php Program Output
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 3 4 <!-- Fig. 29.1: first.php --> 5 <!-- Our first PHP script --> 6 7 <?php $name = "Paul"; // declaration 9 ?> 10 11 <html xmlns = " <head> <title>A simple PHP document</title> </head> 15 <body style = "font-size: 2em"> <p> <strong> 19 <!-- print variable name’s value --> Welcome to PHP, <?php print( "$name" ); ?>! </strong> </p> </body> 25 </html> First.php Program Output Scripting delimiters Declare variable $name Single-line comment Function print outputs the value of variable $name

3 29.2 PHP

4 Assign a string to variable $testString
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " 3 4 <!-- Fig. 29.3: data.php > 5 <!-- Demonstration of PHP data types --> 6 7 <html xmlns = " <head> <title>PHP data types</title> </head> 11 <body> 13 <?php 15 // declare a string, double and integer $testString = "3.5 seconds"; $testDouble = 79.2; $testInteger = 12; ?> 21 <!-- print each variable’s value --> <?php print( $testString ) ?> is a string.<br /> <?php print( $testDouble ) ?> is a double.<br /> <?php print( $testInteger ) ?> is an integer.<br /> 26 <br /> Now, converting to other types:<br /> <?php 30 // call function settype to convert variable // testString to different data types print( "$testString" ); Data.php Assign a string to variable $testString Assign a double to variable $testDouble Assign an integer to variable $testInteger Print each variable’s value

5 Convert variable $testString back to a string
settype( $testString, "double" ); print( " as a double is $testString <br />" ); print( "$testString" ); settype( $testString, "integer" ); print( " as an integer is $testString <br />" ); settype( $testString, "string" ); print( "Converting back to a string results in $testString <br /><br />" ); 42 $value = "98.6 degrees"; 44 // use type casting to cast variables to a // different type print( "Now using type casting instead: <br /> As a string - " . (string) $data . "<br />As a double - " . (double) $data . "<br />As an integer - " . (integer) $data ); ?> </body> 53 </html> Call function settype to convert the data type of variable $testString to a double. Data.php Call function settype to convert the data type of variable $testString to an integer. Convert variable $testString back to a string Use type casting to cast variable $data to different types

6 Program Output

7 Add constant VALUE to variable $a.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " 3 4 <!-- Fig. 29.4: operators.php --> 5 <!-- Demonstration of operators --> 6 7 <html xmlns = " <head> <title>Using arithmetic operators</title> </head> 11 <body> <?php $a = 5; print( "The value of variable a is $a <br />" ); 16 // define constant VALUE define( "VALUE", 5 ); 19 // add constant VALUE to variable $a $a = $a + VALUE; print( "Variable a after adding constant VALUE is $a <br />" ); 24 // multiply variable $a by 2 $a *= 2; print( "Multiplying variable a by 2 yields $a <br />" ); 28 // test if variable $a is less than 50 if ( $a < 50 ) print( "Variable a is less than 50 <br />" ); 32 // add 40 to variable $a $a += 40; print( "Variable a after adding 40 is $a <br />" ); Operators.php Define constant VALUE. Add constant VALUE to variable $a. Multiply variable $a by two using the multiplication assignment operator *=. Test whether variable $a is less than 50 Print if variable $a is less than 50. Add 40 to variable $a using the addition assignment operator +=.

8 Print an uninitialized variable ($nothing).
36 // test if variable $a is 50 or less if ( $a < 51 ) print( "Variable a is still 50 or less<br />" ); 40 // test if variable $a is between 50 and 100, inclusive elseif ( $a < 101 ) print( "Variable a is now between 50 and 100, inclusive<br />" ); else print( "Variable a is now greater than 100 <br />" ); 48 // print an uninitialized variable print( "Using a variable before initializing: $nothing <br />" ); 52 // add constant VALUE to an uninitialized variable $test = $num + VALUE; print( "An uninitialized variable plus constant VALUE yields $test <br />" ); 57 // add a string to an integer $str = "3 dollars"; $a += $str; print( "Adding a string to an integer yields $a <br />" ); ?> </body> 65 </html> Operators.php Print an uninitialized variable ($nothing). Add constant VALUE to an uninitialized variable. Add a string to an integer.

9 Program Output

10 29.2 PHP

11 Create the array $first by assigning a value to an array element.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " 3 4 <!-- Fig. 29.6: arrays.php --> 5 <!-- Array manipulation --> 6 7 <html xmlns = " <head> <title>Array manipulation</title> </head> 11 <body> <?php 14 // create array first print( "<strong>Creating the first array</strong> <br />" ); $first[ 0 ] = "zero"; $first[ 1 ] = "one"; $first[ 2 ] = "two"; $first[] = "three"; 22 // print each element’s index and value for ( $i = 0; $i < count( $first ); $i++ ) print( "Element $i is $first[$i] <br />" ); 26 print( "<br /><strong>Creating the second array </strong><br />" ); 29 // call function array to create array second $second = array( "zero", "one", "two", "three" ); for ( $i = 0; $i < count( $second ); $i++ ) print( "Element $i is $second[$i] <br />" ); 34 Arrays.php Create the array $first by assigning a value to an array element. Assign a value to the array, omitting the index. Appends a new element to the end of the array. Use a for loop to print out each element’s index and value. Function count returns the total number of elements in the array. Call function array to create an array that contains the arguments passed to it. Store the array in variable $second.

12 Assign values to non-numerical indices in array $third.
print( "<br /><strong>Creating the third array </strong><br />" ); 37 // assign values to non-numerical indices $third[ "Harvey" ] = 21; $third[ "Paul" ] = 18; $third[ "Tem" ] = 23; 42 // iterate through the array elements and print each // element’s name and value for ( reset( $third ); $element = key( $third ); next( $third ) ) print( "$element is $third[$element] <br />" ); 48 print( "<br /><strong>Creating the fourth array </strong><br />" ); 51 // call function array to create array fourth using // string indices $fourth = array( "January" => "first", "February" => "second", "March" => "third", "April" => "fourth", "May" => "fifth", "June" => "sixth", "July" => "seventh", "August" => "eighth", "September" => "ninth", "October" => "tenth", "November" => "eleventh","December" => "twelfth" ); 62 // print each element’s name and value foreach ( $fourth as $element => $value ) print( "$element is the $value month <br />" ); ?> </body> 68 </html> Arrays.php Function reset sets the internal pointer to the first element of the array. Assign values to non-numerical indices in array $third. Function key returns the index of the element which the internal pointer references. Function next moves the internal pointer to the next element. Operator => is used in function array to assign each element a string index. The value to the left of the operator is the array index, and the value to the right is the element’s value.

13 Program Output

14 Use a for loop to iterate through each array element.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " 3 4 <!-- Fig. 29.7: compare.php --> 5 <!-- String Comparison > 6 7 <html xmlns = " <head> <title>String Comparison</title> </head> 11 <body> <?php 14 // create array fruits $fruits = array( "apple", "orange", "banana" ); 17 // iterate through each array element for ( $i = 0; $i < count( $fruits ); $i++ ) { 20 // call function strcmp to compare the array element // to string "banana" if ( strcmp( $fruits[ $i ], "banana" ) < 0 ) print( $fruits[ $i ]." is less than banana " ); elseif ( strcmp( $fruits[ $i ], "banana" ) > 0 ) print( $fruits[ $i ]. " is greater than banana " ); else print( $fruits[ $i ]." is equal to banana " ); 30 // use relational operators to compare each element // to string "apple" if ( $fruits[ $i ] < "apple" ) print( "and less than apple! <br />" ); Compare.php Use a for loop to iterate through each array element. Function strcmp compares two strings. If the first string alphabetically precedes the second, then –1 is returned. If the strings are equal, 0 is returned. If the first string alphabetically follows the second, then 1 is returned. Use relational operators to compare each array element to string “apple”.

15 Compare.php Program Output
elseif ( $fruits[ $i ] > "apple" ) print( "and greater than apple! <br />" ); elseif ( $fruits[ $i ] == "apple" ) print( "and equal to apple! <br />" ); 39 } ?> </body> 43 </html> Compare.php Program Output

16 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
" 3 4 <!-- Fig. 29.8: expression.php --> 5 <!-- Using regular expressions --> 6 7 <html xmlns = " <head> <title>Regular expressions</title> </head> 11 <body> <?php $search = "Now is the time"; print( "Test string is: '$search'<br /><br />" ); 16 // call function ereg to search for pattern 'Now' // in variable search if ( ereg( "Now", $search ) ) print( "String 'Now' was found.<br />" ); 21 // search for pattern 'Now' in the beginning of // the string if ( ereg( "^Now", $search ) ) print( "String 'Now' found at beginning of the line.<br />" ); 27 // search for pattern 'Now' at the end of the string if ( ereg( "Now$", $search ) ) print( "String 'Now' was found at the end of the line.<br />" ); 32 Expression.php Function ereg searches for the literal characters Now inside variable $search. The caret special character (^) matches the beginning of a string. Function ereg searches the beginning of the string for pattern Now. The dollar sign special character ($) search for the pattern Now at the end of the string.

17 Expression.php Program Output
// search for any word ending in 'ow' if ( ereg( "[[:<:]]([a-zA-Z]*ow)[[:>:]]", $search, $match ) ) print( "Word found ending in 'ow': " . $match[ 1 ] . "<br />" ); 38 // search for any words beginning with 't' print( "Words beginning with 't' found: "); 41 while ( eregi( "[[:<:]](t[[:alpha:]]+)[[:>:]]", $search, $match ) ) { print( $match[ 1 ] . " " ); 45 // remove the first occurrence of a word beginning // with 't' to find other instances in the string $search = ereg_replace( $match[ 1 ], "", $search ); } 50 print( "<br />" ); ?> </body> 54 </html> The special bracket expressions [[:<:]] and [[:>:]] match the beginning and end of a word, respectively. The expression inside the parentheses, [a-zA-Z]*ow, matches any word ending in ow. The quantifier * matches the preceding pattern 0 or more times. Placing a pattern in parentheses stores the matched string in the array that is specified in the third argument to function ereg. Expression.php Program Output The while loop is used to find each occurrence of a word in the string beginning with t. Function eregi is used to specify case insensitive pattern matches. The pattern used in this example, [[:<:]](t[[:alpha:]]+)[[:>:]], matches any word beginning with the character t followed by one or more characters. Character class [[:alpha:]] recognizes any alphabetic character. After printing a match of a word beginning with t, function ereg_replace is called to remove the word from the string. This is necessary be because to find multiple instances of a given pattern, the first matched instance must first be removed. Function ereg_replace takes three arguments: the pattern to match, a string to replace the matched string and the string to search.

18 29.3 String Processing and Regular Expressions

19 29.4 Viewing Client/Server Environment Variables

20 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
" 3 4 <!-- Fig : globals.php > 5 <!-- Program to display environment variables --> 6 7 <html xmlns = " <head> <title>Environment Variables</title> </head> 11 <body> <table border = "0" cellpadding = "2" cellspacing = "0" width = "100%"> <?php 16 // print the key and value for each element in the // in the $GLOBALS array foreach ( $GLOBALS as $key => $value ) print( "<tr><td bgcolor = \"#11bbff\"> <strong>$key</strong></td> <td>$value</td></tr>" ); ?> </table> </body> 26 </html> Globals.php The foreach loop is used to print out the keys and values for each element in the $GLOBALS array. PHP stores environment variables and their values in the $GLOBALS array.

21 Program Output

22 29.4 Viewing Client/Server Environment Variables

23 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
" 3 4 <!-- Fig : form.html > 5 <!-- Form for use with the form.php program --> 6 7 <html xmlns = " <head> <title>Sample form to take user input in XHTML</title> </head> 11 <body> 13 <h1>This is a sample registration form.</h1> Please fill in all fields and click Register. 16 <!-- post form data to form.php --> <form method = "post" action = "form.php"> <img src = "images/user.gif" alt = "User" /><br /> <span style = "color: blue"> Please fill out the fields below.<br /> </span> 23 <!-- create four text boxes for user input --> <img src = "images/fname.gif" alt = "First Name" /> <input type = "text" name = "fname" /><br /> 27 <img src = "images/lname.gif" alt = "Last Name" /> <input type = "text" name = "lname" /><br /> 30 <img src = "images/ .gif" alt = " " /> <input type = "text" name = " " /><br /> 33 <img src = "images/phone.gif" alt = "Phone" /> <input type = "text" name = "phone" /><br /> form.html The action attribute of the form element indicates that when the user clicks Register, the form data will be posted to form.php. A unique name (e.g., ) is assigned to each of the form’s input fields. When Register is clicked, each field’s name and value are sent to the Web server.

24 form.html 36 37 <span style = "font-size: 10pt">
Must be in the form (555) </span> <br /><br /> 40 <img src = "images/downloads.gif" alt = "Publications" /><br /> 43 <span style = "color: blue"> Which book would you like information about? </span><br /> 47 <!-- create drop-down list containing book names --> <select name = "book"> <option>Internet and WWW How to Program 2e</option> <option>C++ How to Program 3e</option> <option>Java How to Program 4e</option> <option>XML How to Program 1e</option> </select> <br /><br /> 56 <img src = "images/os.gif" alt = "Operating System" /> <br /><span style = "color: blue"> Which operating system are you currently using? <br /></span> 61 <!-- create five radio buttons --> <input type = "radio" name = "os" value = "Windows NT" checked = "checked" /> Windows NT 66 <input type = "radio" name = "os" value = "Windows 2000" /> Windows 2000 70 form.html

25 form.html 71 <input type = "radio" name = "os" value =
"Windows 98" /> Windows 98<br /> 74 <input type = "radio" name = "os" value = "Linux" /> Linux 77 <input type = "radio" name = "os" value = "Other" /> Other<br /> 80 <!-- create a submit button --> <input type = "submit" value = "Register" /> </form> 84 </body> 86 </html> form.html

26 Program Output

27 The expression \( matches the opening parentheses of a phone number.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " 3 4 <!-- Fig : form.php > 5 <!-- Read information sent from form.html --> 6 7 <html xmlns = " <head> <title>Form Validation</title> </head> 11 <body style = "font-family: arial,sans-serif"> 13 <?php 15 // determine if phone number is valid and print // an error message if not if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) ){ 20 print( "<p><span style = \"color: red; font-size: 2em\"> INVALID PHONE NUMBER</span><br /> A valid phone number must be in the form <strong>(555) </strong><br /> <span style = \"color: blue\"> Click the Back button, enter a valid phone number and resubmit.<br /><br /> Thank You.</span></p></body></html>" ); 30 die(); // terminate script execution } ?> 34 Form.php Function ereg is called to determine whether the phone number entered by the user is valid. The parentheses in the expression must be followed by three digits ([0-9]{3}), a closing parenthesis, three digits, a literal hyphen and four additional digits. The expression \( matches the opening parentheses of a phone number. We access the phone field’s value from form.html by using variable $phone. Function die terminates script execution

28 Form.php 35 <p>Hi 36 <span style = "color: blue">
<strong> <?php print( "$fname" ); ?> </strong> </span>. Thank you for completing the survey.<br /> 42 You have been added to the <span style = "color: blue"> <strong> <?php print( "$book " ); ?> </strong> </span> mailing list. </p> <strong>The following information has been saved in our database:</strong><br /> 53 <table border = "0" cellpadding = "0" cellspacing = "10"> <tr> <td bgcolor = "#ffffaa">Name </td> <td bgcolor = "#ffffbb"> </td> <td bgcolor = "#ffffcc">Phone</td> <td bgcolor = "#ffffdd">OS</td> </tr> 61 <tr> <?php 64 // print each form field’s value print( "<td>$fname $lname</td> <td>$ </td> <td>$phone</td> <td>$os</td>" ); Form.php

29 Form.php Program Output
?> </tr> </table> 73 <br /><br /><br /> <div style = "font-size: 10pt; text-align: center"> This is only a sample form. You have not been added to a mailing list. </div> </body> 80 </html> Form.php Program Output

30 Form data is posted to password.php.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " 3 4 <!-- Fig : password.html > 5 <!-- XHTML form sent to password.php for verification --> 6 7 <html xmlns = " <head> <title>Verifying a username and a password.</title> 10 <style type = "text/css"> td { background-color: #DDDDDD } </style> </head> 15 <body style = "font-family: arial"> <p style = "font-size: 13pt"> Type in your username and password below. <br /> <span style = "color: #0000FF; font-size: 10pt; font-weight: bold"> Note that password will be sent as plain text </span> </p> 25 <!-- post form data to password.php --> <form action = "password.php" method = "post"> <br /> 29 <table border = "0" cellspacing = "0" style = "height: 90px; width: 123px; font-size: 10pt" cellpadding = "0"> 33 Password.html Form data is posted to password.php.

31 Password.html 34 <tr> 35 <td colspan = "3">
<strong>Username:</strong> </td> </tr> 39 <tr> <td colspan = "3"> <input size = "40" name = "USERNAME" style = "height: 22px; width: 115px" /> </td> </tr> 46 <tr> <td colspan = "3"> <strong>Password:</strong> </td> </tr> 52 <tr> <td colspan = "3"> <input size = "40" name = "PASSWORD" style = "height: 22px; width: 115px" type = "password" /> <br/></td> </tr> 60 <tr> <td colspan = "1"> <input type = "submit" name = "Enter" value = "Enter" style = "height: 23px; width: 47px" /> </td> <td colspan = "2"> <input type = "submit" name = "NewUser" Password.html

32 Password.html Program Output
value = "New User" style = "height: 23px" /> </td> </tr> </table> </form> </body> 76 </html> Password.html Program Output

33 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
" 3 4 <!-- Fig : password.php > 5 <!-- Searching a database for usernames and passwords. --> 6 7 <html xmlns = " <head> <?php 10 // check if user has left USERNAME // or PASSWORD field blank if ( !$USERNAME || !$PASSWORD ) { fieldsBlank(); die(); } 17 // check if the New User button was clicked if ( isset( $NewUser ) ) { 20 // open password.txt for writing using append mode if ( !( $file = fopen( "password.txt", "append" ) ) ) { 24 // print error message and terminate script // execution if file cannot be opened print( "<title>Error</title></head><body> Could not open password file </body></html>" ); die(); } 32 Password.php Variable names, when preceded by the logical negation operator (!), return true if they are empty or set to 0. This checks if a user has submitted a form without specifying a username or password. Function isset tests whether the user has pressed the New User button, indicating that a new user must be added. Function fieldsBlank is called if the user has submitted an incomplete form to notify the user that all form fields must be completed. To add a new user, we open the file password.txt in append mode and assign the file handle that is returned to variable $file. Print an error message and terminate script execution if the file cannot be opened.

34 Function fputs writes the name and password to the text file..
// write username and password to file and // call function userAdded fputs( $file, "$USERNAME,$PASSWORD\n" ); userAdded( $USERNAME ); } else { 39 // if a new user is not being added, open file // for reading if ( !( $file = fopen( "password.txt", "read" ) ) ) { print( "<title>Error</title></head> <body>Could not open password file </body></html>" ); die(); } 49 $userVerified = 0; 51 // read each line in file and check username // and password while ( !feof( $file ) && !$userVerified ) { 55 // read line from file $line = fgets( $file, 255 ); 58 // remove newline character from end of line $line = chop( $line ); 61 // split username and password $field = split( ",", $line, 2 ); 64 // verify username if ( $USERNAME == $field[ 0 ] ) { $userVerified = 1; Function fputs writes the name and password to the text file.. Password.php Function userAdded is called to print a message to the user to indicate that the username and password were added to the file. If variable $NewUser has not been set, we assume that the user has pressed the Enter button, and call function fopen to open the file in read mode. Before entering the while loop, variable $userVerified is set to 0. The while loop executes as long as the there are more lines in the file to read and variable $userVerified is still 0 or empty. Function fgets reads a line from the text file. The result is assigned to variable $line. Function chop removes the newline character from the end of the line. Function split is called to separate the string at the specified delimiter (in this case, a comma). The resulting array is stored in array $field. The username entered by the user is tested against the one returned in the text file (stored in the first element of the array). If they match, variable $userVerified is set to 1.

35 68 // call function checkPassword to verify // user’s password if ( checkPassword( $PASSWORD, $field ) == true ) accessGranted( $USERNAME ); else wrongPassword(); } } 78 // close text file fclose( $file ); 81 // call function accessDenied if username has // not been verified if ( !$userVerified ) accessDenied(); } 87 // verify user password and return a boolean function checkPassword( $userpassword, $filedata ) { if ( $userpassword == $filedata[ 1 ] ) return true; else return false; } 96 Password.php Function checkPassword is called to verify the user’s password. Variable $PASSWORD and array $field are passed to the function. If variable $userVerified has not been set to a value other than 0, function accessDenied is called to notify the client that access has been denied. If function checkPassword returns true, function accessGranted is called to notify the client that permission has been granted. Otherwise, function wrongPassword is called. After the while loop has executed, function fclose is called to close the file. Function checkPassword compares the user’s password to the password in the file. If they match, true is returned, whereas false is returned if they do not.

36 97 // print a message indicating the user has been added
function userAdded( $name ) { print( "<title>Thank You</title></head> <body style = \"font-family: arial; font-size: 1em; color: blue\"> <strong>You have been added to the user list, $name. <br />Enjoy the site.</strong>" ); } 107 // print a message indicating permission // has been granted function accessGranted( $name ) { print( "<title>Thank You</title></head> <body style = \"font-family: arial; font-size: 1em; color: blue\"> <strong>Permission has been granted, $name. <br /> Enjoy the site.</strong>" ); } 119 // print a message indicating password is invalid function wrongPassword() { print( "<title>Access Denied</title></head> <body style = \"font-family: arial; font-size: 1em; color: red\"> <strong>You entered an invalid password.<br />Access has been denied.</strong>" ); } 130 Password.php Function accessGranted prints a message to the client indicating that permission has been granted. Function userAdded prints a message to the client indicating that the user has been added. Function wrongPassword prints a message to the client indicating that the password is invalid.

37 131 // print a message indicating access has been denied
function accessDenied() { print( "<title>Access Denied</title></head> <body style = \"font-family: arial; font-size: 1em; color: red\"> <strong> You were denied access to this server. <br /></strong>" ); } 141 // print a message indicating that fields // have been left blank function fieldsBlank() { print( "<title>Access Denied</title></head> <body style = \"font-family: arial; font-size: 1em; color: red\"> <strong> Please fill in all form fields. <br /></strong>" ); } ?> </body> 155 </html> Function accessDenied prints a message to the client indicating that access has been denied. Password.php Function fieldsBlank prints a message to the client indicating that all form fields have not been completed.

38 Program Output

39 Fig. 29.17 Database password.txt containing usernames and passwords.
1 account1,password1 2 account2,password2 3 account3,password3 4 account4,password4 5 account5,password5 6 account6,password6 7 account7,password7 8 account8,password8 9 account9,password9 10 account10,password10 Password.txt Fig Database password.txt containing usernames and passwords.

40 Select box containing options for a SELECT query.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " 3 4 <!-- Fig : data.html > 5 <!-- Querying a MySQL Database --> 6 7 <html xmlns = " <head> <title>Sample Database Query</title> </head> 11 <body style = "background-color: #F0E68C"> <h2 style = "font-family: arial color: blue"> Querying a MySQL database. </h2> 16 <form method = "post" action = "database.php"> <p>Select a field to display: 19 <!-- add a select box containing options --> <!-- for SELECT query > <select name = "select"> <option selected = "selected">*</option> <option>ID</option> <option>Title</option> <option>Category</option> <option>ISBN</option> </select> </p> 30 Data.html Select box containing options for a SELECT query.

41 Data.html Program Output
<input type = "submit" value = "Send Query" style = "background-color: blue; color: yellow; font-weight: bold" /> </form> </body> 36 </html> Data.html Program Output

42 Build the select query and assign the string to variable $query.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " 3 4 <!-- Fig : database.php > 5 <!-- Program to query a database and --> 6 <!-- send results to the client > 7 8 <html xmlns = " <head> <title>Search Results</title> </head> 12 <body style = "font-family: arial, sans-serif" style = "background-color: #F0E68C"> <?php 16 // build SELECT query $query = "SELECT " . $select . " FROM Books"; 19 // Connect to MySQL if ( !( $database = mysql_connect( "localhost", "httpd", "" ) ) ) die( "Could not connect to database" ); 24 // open Products database if ( !mysql_select_db( "Products", $database ) ) die( "Could not open Products database" ); 28 // query Products database if ( !( $result = mysql_query( $query, $database ) ) ) { print( "Could not execute query! <br />" ); die( mysql_error() ); } ?> 35 Database.php Build the select query and assign the string to variable $query. Function mysql_connect returns a database handle which represents PHP’s connection to a database. If this connection is not made, function die is called to terminate script execution. Function mysql_select_db is called to specify the database to be queried. Function mysql_query returns an object containing the result set of the query, which we assign to variable $result.

43 The total number of results are printed to the client.
<h3 style = "color: blue"> Search Results</h3> 38 <table border = "1" cellpadding = "3" cellspacing = "2" style = "background-color: #ADD8E6"> 41 <?php 43 // fetch each record in result set for ( $counter = 0; $row = mysql_fetch_row( $result ); $counter++ ){ 48 // build table to display results print( "<tr>" ); 51 foreach ( $row as $key => $value ) print( "<td>$value</td>" ); 54 print( "</tr>" ); } 57 mysql_close( $database ); ?> 60 </table> 62 <br />Your search yielded <strong> <?php print( "$counter" ) ?> results.<br /><br /></strong> 65 <h5>Please comments to <a href = Deitel and Associates, Inc. </a> </h5> Database.php The for loop iterates through each record in the result set while constructing an XHTML table from the results. Variable $counter is incremented by one for each row retrieved. Function mysql_fetch_row returns an array containing the elements of each row in the result set of our query ($result). The foreach loop iterates through the array containing the elements of each row and prints out each element in an individual table cell. The total number of results are printed to the client.

44 Database.php Program Output
71 </body> 73 </html> Database.php Program Output

45 Form data is posted to cookies.php.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " 3 4 <!-- Fig : cookies.html --> 5 <!-- Writing a Cookie > 6 7 <html xmlns = " <head> <title>Writing a cookie to the client computer</title> </head> 11 <body style = "font-family: arial, sans-serif; background-color: #99CCFF"> 14 <h2>Click Write Cookie to save your cookie data.</h2> 16 <form method = "post" action = "cookies.php" style = "font-size: 10pt"> <strong>Name:</strong><br /> <input type = "text" name = "NAME" /><br /> 21 <strong>Height:</strong><br /> <input type = "text" name = "HEIGHT" /><br /> 24 <strong>Favorite Color:</strong><br /> <input type = "text" name = "COLOR" /><br /> 27 <input type = "submit" value = "Write Cookie" style = "background-color: #F0E86C; color: navy; font-weight: bold" /></p> </form> </body> 33 </html> Cookies.html Form data is posted to cookies.php.

46 Program Output

47 1 <?php // Fig : cookies.php // Program to write a cookie to a client's machine 4 // write each form field’s value to a cookie and set the // cookie’s expiration date setcookie( "Name", $NAME, time() + 60 * 60 * 24 * 5 ); setcookie( "Height", $HEIGHT, time() + 60 * 60 * 24 * 5 ); setcookie( "Color", $COLOR, time() + 60 * 60 * 24 * 5 ); 10 ?> 11 12 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " 14 15 <html xmlns = " <head> <title>Cookie Saved</title> </head> 19 <body style = "font-family: arial, sans-serif"> <p>The cookie has been set with the following data:</p> 22 <!-- print each form field’s value --> <br /><span style = "color: blue">Name:</span> <?php print( $NAME ) ?><br /> 26 <span style = "color: blue">Height:</span> <?php print( $HEIGHT ) ?><br /> 29 <span style = "color: blue">Favorite Color:</span> 31 Cookies.php Function setcookie takes the name of the cookie to be set as the first argument, followed by the value to be stored in the cookie. The optional third argument specifies the expiration date of the cookie. Each form field’s value is printed to confirm the data that has been set as a cookie with the user.

48 Cookies.php Program Output
<span style = "color: <?php print( "$COLOR\">$COLOR" ) ?> </span><br /> <p>Click <a href = "readCookies.php">here</a> to read the saved cookie.</p> </body> 37 </html> Hyperlink to readCookies.php. Cookies.php Program Output

49 29.8 Cookies Fig. 29.22 Cookies directory before a cookie is written.
Fig Cookies directory after a cookie is written.

50 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
" 3 4 <!-- Fig : readCookies.php > 5 <!-- Program to read cookies from the client's computer --> 6 7 <html xmlns = " <head><title>Read Cookies</title></head> 9 <body style = "font-family: arial, sans-serif"> 11 <p> <strong> The following data is saved in a cookie on your computer. </strong> </p> 18 <table border = "5" cellspacing = "0" cellpadding = "10"> <?php 21 // iterate through array $HTTP_COOKIE_VARS and print // name and value of each cookie foreach ( $HTTP_COOKIE_VARS as $key => $value ) print( "<tr> <td bgcolor=\"#F0E68C\">$key</td> <td bgcolor=\"#FFA500\">$value</td> </tr>" ); ?> 30 </table> </body> 33 </html> ReadCookies.php PHP creates array $HTTP_COOKIE_VARS which contains all cookie values indexed by their names. The foreach loop iterates through the $HTTP_COOKIE_VARS array and prints the name and value of each cookie in an XHTML table.

51 Program Output

52 29.9 Operator Precedence

53 29.9 Operator Precedence

54 29.9 Operator Precedence


Download ppt "Chapter 29 - PHP Outline 29.1 Introduction 29.2 PHP"

Similar presentations


Ads by Google