Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: " 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP."— Presentation transcript:

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

2  2008 Pearson Education, Inc. All rights reserved. 2

3 3 Conversion for me was not a Damascus Road experience. I slowly moved into a intellectual acceptance of what my intuition had always known. — Madeleine L’Engle Be careful when reading health books; you may die of a misprint. — Mark Twain

4  2008 Pearson Education, Inc. All rights reserved. 4 Reckoners without their host must reckon twice. — John Heywood There was a door to which I found no key; There was the veil through which I might not see. — Omar Khayyam

5  2008 Pearson Education, Inc. All rights reserved. 5 OBJECTIVES In this chapter you will learn:  To manipulate data of various types.  To use operators, arrays and control statements.  To use regular expressions to search for patterns.  To construct programs that process form data.  To store data on the client using cookies.  To create programs that interact with MySQL databases.

6  2008 Pearson Education, Inc. All rights reserved. 6 23.1Introduction 23.2 PHP Basics 23.3 String Processing and Regular Expressions 23.3.1 Comparing Strings 23.3.2 Regular Expressions 23.4 Form Processing and Business Logic 23.5 Connecting to a Database 23.6 Using Cookies 23.7 Dynamic Content 23.8 Operator Precedence Chart 23.9 Wrap-Up 23.10 Web Resources

7  2008 Pearson Education, Inc. All rights reserved. 7 23.1 Introduction PHP, or PHP: Hypertext Preprocessor, has become one of the most popular server-side scripting languages for creating dynamic web pages. PHP is open source and platform independent— implementations exist for all major UNIX, Linux, Mac and Windows operating systems. PHP also supports a large number of databases.

8  2008 Pearson Education, Inc. All rights reserved. 8 23.2 PHP Basics The power of the web resides not only in serving content to users, but also in responding to requests from users and generating web pages with dynamic content. PHP code is embedded directly into XHTML documents, though these script segments are interpreted by a server before being delivered to the client. PHP script file names end with.php. Although PHP can be used from the command line, a web server is necessary to take full advantage of the scripting language. In PHP, code is inserted between the scripting delimiters. PHP code can be placed anywhere in XHTML markup, as long as the code is enclosed in these delimiters.

9  2008 Pearson Education, Inc. All rights reserved. 9 23.2 PHP Basics (Cont.) Variables are preceded by a $ and are created the first time they are encountered. PHP statements terminate with a semicolon ( ; ). Single-line comments which begin with two forward slashes ( // ) or a pound sign ( # ). Text to the right of the delimiter is ignored by the interpreter. Multiline comments begin with delimiter /* and end with delimiter */. When a variable is encountered inside a double-quoted ( "" ) string, PHP interpolates the variable. In other words, PHP inserts the variable’s value where the variable name appears in the string. All operations requiring PHP interpolation execute on the server before the XHTML document is sent to the client. PHP variables are loosely typed—they can contain different types of data at different times.

10  2008 Pearson Education, Inc. All rights reserved. 10 Outline first.php Delimiters enclosing PHP script Declares and initializes a PHP variable Interpolates the variable so that its value will be output to the XHTML document

11  2008 Pearson Education, Inc. All rights reserved. 11 Common Programming Error 23.1 Failing to precede a variable name with a $ is a syntax error.

12  2008 Pearson Education, Inc. All rights reserved. 12 Common Programming Error 23.2 Variable names in PHP are case sensitive. Failure to use the proper mixture of cases to refer to a variable will result in a logic error, since the script will create a new variable for any name it doesn’t recognize as a previously used variable.

13  2008 Pearson Education, Inc. All rights reserved. 13 Common Programming Error 23.3 Forgetting to terminate a statement with a semicolon ( ; ) is a syntax error.

14  2008 Pearson Education, Inc. All rights reserved. 14 Fig. 23.2 | PHP types.

15  2008 Pearson Education, Inc. All rights reserved. 15 23.2 PHP Basics (Cont.) Type conversions can be performed using function settype. This function takes two arguments—a variable whose type is to be changed and the variable’s new type. Variables are automatically converted to the type of the value they are assigned. Function gettype returns the current type of its argument. Calling function settype can result in loss of data. For example, doubles are truncated when they are converted to integers. When converting from a string to a number, PHP uses the value of the number that appears at the beginning of the string. If no number appears at the beginning, the string evaluates to 0. Another option for conversion between types is casting (or type casting). Casting does not change a variable’s content—it creates a temporary copy of a variable’s value in memory. The concatenation operator (. ) combines multiple strings. A print statement split over multiple lines prints all the data that is enclosed in its parentheses.

16  2008 Pearson Education, Inc. All rights reserved. 16 Outline data.php (1 of 3) Automatically declares a string Automatically declares a double Automatically declares an integer Outputs the type of $testString

17  2008 Pearson Education, Inc. All rights reserved. 17 Outline data.php (2 of 3) Modifies $testString to be a double Modifies $testString to be an integer Modifies $testString to be a string

18  2008 Pearson Education, Inc. All rights reserved. 18 Outline data.php (3 of 3) Temporarily casts $data as a double and an integer Concatenation

19  2008 Pearson Education, Inc. All rights reserved. 19 Error-Prevention Tip 23.1 Function print can be used to display the value of a variable at a particular point during a program’s execution. This is often helpful in debugging a script.

20  2008 Pearson Education, Inc. All rights reserved. 20 23.2 PHP Basics (Cont.) Function define creates a named constant. It takes two arguments—the name and value of the constant. An optional third argument accepts a boolean value that specifies whether the constant is case insensitive— constants are case sensitive by default. Uninitialized variables have the value undef, which has different values, depending on its context. In a numeric context, it evaluates to 0. In a string context, it evaluates to an empty string ( "" ). Keywords may not be used as identifiers.

21  2008 Pearson Education, Inc. All rights reserved. 21 Common Programming Error 23.4 Assigning a value to a constant after it is declared is a syntax error.

22  2008 Pearson Education, Inc. All rights reserved. 22 Outline operators.php (1 of 3) Creates the named constant VALUE with a value of 5 Equivalent to $a = $a * 2

23  2008 Pearson Education, Inc. All rights reserved. 23 Outline operators.php (2 of 3) Uses a comparison operator with a variable and an integer Uninitialized variable $num evaluates to 0

24  2008 Pearson Education, Inc. All rights reserved. 24 Outline operators.php (3 of 3) $str is converted to an integer for this operation

25  2008 Pearson Education, Inc. All rights reserved. 25 Error-Prevention Tip 23.2 Initialize variables before they are used to avoid subtle errors. For example, multiplying a number by an uninitialized variable results in 0.

26  2008 Pearson Education, Inc. All rights reserved. 26 Fig. 23.5 | PHP keywords.

27  2008 Pearson Education, Inc. All rights reserved. 27 23.2 PHP Basics (Cont.) PHP provides the capability to store data in arrays. Arrays are divided into elements that behave as individual variables. Array names, like other variables, begin with the $ symbol. Individual array elements are accessed by following the array’s variable name with an index enclosed in square brackets ( [] ). If a value is assigned to an array that does not exist, then the array is created. Likewise, assigning a value to an element where the index is omitted appends a new element to the end of the array. Function count returns the total number of elements in the array. Function array creates an array that contains the arguments passed to it. The first item in the argument list is stored as the first array element (index 0 ), the second item is stored as the second array element and so on.

28  2008 Pearson Education, Inc. All rights reserved. 28 23.2 PHP Basics (Cont.) Arrays with nonnumeric indices are called associative arrays. You can create an associative array using the operator =>, where the value to the left of the operator is the array index and the value to the right is the element’s value. PHP provides functions for iterating through the elements of an array. Each array has a built-in internal pointer, which points to the array element currently being referenced. Function reset sets the internal pointer to the first array element. Function key returns the index of the element currently referenced by the internal pointer, and function next moves the internal pointer to the next element. The foreach statement, designed for iterating through arrays, starts with the array to iterate through, followed by the keyword as, followed by two variables—the first is assigned the index of the element and the second is assigned the value of that index’s element. (If only one variable is listed after as, it is assigned the value of the array element.)

29  2008 Pearson Education, Inc. All rights reserved. 29 Outline arrays.php (1 of 4) Sets the first element of array $first to the string “zero” Automatically creates array $first “three” is appended to the end of array $first Returns the number of elements in the array

30  2008 Pearson Education, Inc. All rights reserved. 30 Outline arrays.php (2 of 4) Function array creates array $second with its arguments as elements Creates associative array $third Sets the internal pointer to the first array element in $third Returns the index of the element being pointed to Moves the internal pointer to the next element and returns it

31  2008 Pearson Education, Inc. All rights reserved. 31 Outline arrays.php (3 of 4) Uses operator => to initialize the element with index “January” to have value “first” Iterates through each element in array $fourth Stores the index of the element Stores the value of the element

32  2008 Pearson Education, Inc. All rights reserved. 32 Outline arrays.php (4 of 4)

33  2008 Pearson Education, Inc. All rights reserved. 33 23.3 String Processing and Regular Expressions A regular expression is a series of characters used for pattern-matching templates in strings, text files and databases. Many string-processing tasks can be accomplished using the equality and relational operators ( ==, !=, and >= ). Function strcmp compares two strings. The function returns -1 if the first string alphabetically precedes the second string, 0 if the strings are equal, and 1 if the first string alphabetically follows the second.

34  2008 Pearson Education, Inc. All rights reserved. 34 Outline compare.php (1 of 2) Checks whether the ith element of the fruits array preceeds the string banana

35  2008 Pearson Education, Inc. All rights reserved. 35 Outline compare.php (2 of 2) Uses relational operators to compare the element of the fruits array with the string apple

36  2008 Pearson Education, Inc. All rights reserved. 36 23.3 String Processing and Regular Expressions (Cont.) Functions ereg and preg_match use regular expressions to search a string for a specified pattern. If a pattern is found using ereg, it returns the length of the matched string— which evaluates to true in a boolean context. Anything enclosed in single quotes in a print statement is not interpolated (unless the single quotes are nested in a double-quoted string literal). Function ereg receives a regular expression pattern to search for and the string to search. Function eregi performs case-insensitive pattern matches. Regular expressions can include metacharacters that specify patterns. For example, the caret ( ^ ) metacharacter matches the beginning of a string, while the dollar sign ( $ ) matches the end of a string. The period (. ) metacharacter matches any single character. Bracket expressions are lists of characters enclosed in square brackets ( [] ) that match any single character from the list. Ranges can be specified by supplying the beginning and the end of the range separated by a dash ( - ).

37  2008 Pearson Education, Inc. All rights reserved. 37 23.3 String Processing and Regular Expressions (Cont.) The special bracket expressions [[: :]] match the beginning and end of a word, respectively. Quantifiers are used in regular expressions to denote how often a particular character or set of characters can appear in a match. The optional third argument to function ereg is an array that stores matches to each parenthetical statement of the regular expression. The first element stores the string matched for the entire pattern, and the remaining elements are indexed from left to right. To find multiple instances of a given pattern, we must make multiple calls to ereg, and remove matched instances before calling the function again by using a function such as ereg_replace. Character classes, or sets of specific characters, are enclosed by the delimiters [: and :]. When this expression is placed in another set of brackets, it is a regular expression matching all of the characters in the class. A bracketed expression containing two or more adjacent character classes in the class delimiters represents those character sets combined. Function ereg_replace takes three arguments—the pattern to match, a string to replace the matched string and the string to search. The modified string is returned.

38  2008 Pearson Education, Inc. All rights reserved. 38 Outline expression.php (1 of 2) String to search Searches for the string “Now” in $search Checks if string “Now” appears at the beginning of $search Checks if string “Now” appears at the end of $search

39  2008 Pearson Education, Inc. All rights reserved. 39 Outline expression.php (2 of 2) Searches for a word ending in “ow” and stores matches in $match array Prints first encountered instance of word ending in “ow” Performs a case- insensitive search for words beginning with the letter “t” Replaces the found instance from the previous call to eregi with an empty string so that the next instance of the pattern can be found and stored in $match

40  2008 Pearson Education, Inc. All rights reserved. 40 Fig. 23.9 | Some PHP quantifiers.

41  2008 Pearson Education, Inc. All rights reserved. 41 Fig. 23.10 | Some PHP character classes.

42  2008 Pearson Education, Inc. All rights reserved. 42 23.4 Form Processing and Business Logic Superglobal arrays are associative arrays predefined by PHP that hold variables acquired from user input, the environment or the web server and are accessible in any variable scope. The arrays $_GET and $_POST retrieve information sent to the server by HTTP get and post requests, respectively. Using method = "post" appends form data to the browser request that contains the protocol and the requested resource’s URL. Scripts located on the web server’s machine can access the form data sent as part of the request.

43  2008 Pearson Education, Inc. All rights reserved. 43 Fig. 23.11 | Some useful superglobal arrays.

44  2008 Pearson Education, Inc. All rights reserved. 44 Outline form.html (1 of 4) Appends form data to the browser request that contains the protocol and the URL of the requested resource Form data is posted to form.php to be processed

45  2008 Pearson Education, Inc. All rights reserved. 45 Outline form.html (2 of 4) Creates form fields Creates drop-down list with book names

46  2008 Pearson Education, Inc. All rights reserved. 46 Outline form.html (3 of 4) Creates radio buttons with “Windows XP” initially selected

47  2008 Pearson Education, Inc. All rights reserved. 47 Outline form.html (4 of 4)

48  2008 Pearson Education, Inc. All rights reserved. 48 Good Programming Practice 23.1 Use meaningful XHTML object names for input fields. This makes PHP scripts that retrieve form data easier to understand.

49  2008 Pearson Education, Inc. All rights reserved. 49 23.4 Form Processing and Business Logic (Cont.) Function extract creates a variable/value pair corresponding to each key/value pair in the associative array passed as an argument. Business logic, or business rules, ensures that only valid information is stored in databases. We escape the normal meaning of a character in a string by preceding it with the backslash character ( \ ). Function die terminates script execution. The function’s optional argument is a string, which is printed as the script exits.

50  2008 Pearson Education, Inc. All rights reserved. 50 Outline form.php (1 of 5)

51  2008 Pearson Education, Inc. All rights reserved. 51 Outline form.php (2 of 5) Creates a variable/value pair for each key/value pair in $_POST Ensures that phone number is in proper format Terminates execution and closes the document properly

52  2008 Pearson Education, Inc. All rights reserved. 52 Outline form.php (3 of 5) Prints the value entered in the email field in form.html

53  2008 Pearson Education, Inc. All rights reserved. 53 Outline form.php (4 of 5)

54  2008 Pearson Education, Inc. All rights reserved. 54 Outline form.php (5 of 5)

55  2008 Pearson Education, Inc. All rights reserved. 55 Software Engineering Observation 23.1 Use business logic to ensure that invalid information is not stored in databases. When possible, validate important or sensitive form data on the server, since JavaScript may be disabled by the client. Some data, such as passwords, must always be validated on the server side.

56  2008 Pearson Education, Inc. All rights reserved. 56 Error-Prevention Tip 23.3 Be sure to close any open XHTML tags when calling function die. Not doing so can produce invalid XHTML output that will not display properly in the client browser. Function die has an optional parameter that specifies a message to output when exiting, so one technique for closing tags is to close all open tags using die, as in die(" ").

57  2008 Pearson Education, Inc. All rights reserved. 57 23.5 Connecting to a Database Function mysql_connect connects to the MySQL database. It takes three arguments—the server’s hostname, a username and a password, and returns a database handle—a representation of PHP’s connection to the database, or false if the connection fails. Function mysql_select_db specifies the database to be queried, and returns a bool indicating whether or not it was successful. To query the database, we call function mysql_query, specifying the query string and the database to query. This returns a resource containing the result of the query, or false if the query fails. It can also execute SQL statements such as INSERT or DELETE that do not return results. Function mysql_error returns any error strings from the database. mysql_close closes the connection to the database specified in its argument.

58  2008 Pearson Education, Inc. All rights reserved. 58 Outline data.html (1 of 2) Posts data to database.php

59  2008 Pearson Education, Inc. All rights reserved. 59 Outline data.html (2 of 2) Creates drop-down menu specifying which data to output to the screen, with * (all data) as the default selection

60  2008 Pearson Education, Inc. All rights reserved. 60 Outline database.php (1 of 3) Builds a SELECT query with the selection made in data.html

61  2008 Pearson Education, Inc. All rights reserved. 61 Outline database.php (2 of 3) Connects to database using server hostname localhost and username and password “iw3htp4” Specifies products as the database to be queried Queries $database with $query Returns any error strings from the database Closes the connection to the database Returns an array with the values for each column of the current row in $result

62  2008 Pearson Education, Inc. All rights reserved. 62 Outline database.php (3 of 3)

63  2008 Pearson Education, Inc. All rights reserved. 63 23.6 Using Cookies A cookie is a text file that a website stores on a client’s computer to maintain information about the client during and between browsing sessions. A server can access only the cookies that it has placed on the client. Function setcookie takes the name of the cookie to be set as the first argument, followed by the value to be stored in the cookie. The optional third argument indicates the expiration date of the cookie. A cookie without a third argument is known as a session cookie, while one with an expiration date is a persistent cookie. If only the name argument is passed to function setcookie, the cookie is deleted from the client’s computer. Cookies defined in function setcookie are sent to the client at the same time as the information in the HTTP header; therefore, it needs to be called before any XHTML is printed. The current time is returned by function time.

64  2008 Pearson Education, Inc. All rights reserved. 64 Outline cookies.html (1 of 2) Posts form data to cookies.php Creates fields to gather information to be written into a cookie

65  2008 Pearson Education, Inc. All rights reserved. 65 Outline cookies.html (2 of 2) Form field

66  2008 Pearson Education, Inc. All rights reserved. 66 Outline cookies.php (1 of 2) Creates a cookie for each entered value and sets the expiration date to be five days after the current time

67  2008 Pearson Education, Inc. All rights reserved. 67 Outline cookies.php (2 of 2) Links to the page that displays the contents of the cookie

68  2008 Pearson Education, Inc. All rights reserved. 68 Software Engineering Observation 23.2 Some clients do not accept cookies. When a client declines a cookie, the browser application normally informs the user that the site may not function correctly without cookies enabled.

69  2008 Pearson Education, Inc. All rights reserved. 69 Software Engineering Observation 23.3 Cookies should not be used to store e-mail addresses or private data on a client’s computer.

70  2008 Pearson Education, Inc. All rights reserved. 70 23.6 Using Cookies (Cont.) When using Internet Explorer, cookies are stored in a Cookies directory on the client’s machine. In Firefox, cookies are stored in a file named cookies.txt.

71  2008 Pearson Education, Inc. All rights reserved. 71 Fig. 23.18 | IE7’s Cookies directory before a cookie is written.

72  2008 Pearson Education, Inc. All rights reserved. 72 Fig. 23.19 | IE7’s Cookies directory after a cookie is written.

73  2008 Pearson Education, Inc. All rights reserved. 73 23.6 Using Cookies (Cont.) PHP creates the superglobal array $_COOKIE, which contains all the cookie values indexed by their names.

74  2008 Pearson Education, Inc. All rights reserved. 74 Outline readCookies.php (1 of 2)

75  2008 Pearson Education, Inc. All rights reserved. 75 Outline readCookies.php (2 of 2) Iterates through all values in $_COOKIE

76  2008 Pearson Education, Inc. All rights reserved. 76 23.7 Dynamic Content Function isset allows you to find out if a variable has a value. A variable variable ( $$variable ) allows the code to reference variables dynamically. You can use this expression to obtain the value of the variable whose name is equal to the value of $variable. The quotemeta function inserts a backslash ( \ ) before any special characters in the passed string.

77  2008 Pearson Education, Inc. All rights reserved. 77 Outline dynamicForm.php (1 of 12)

78  2008 Pearson Education, Inc. All rights reserved. 78 Outline dynamicForm.php (2 of 12) Checks whether the Register button has been pressed Checks that the first name field is not blank Makes an entry in the error array Sets $iserror to true

79  2008 Pearson Education, Inc. All rights reserved. 79 Outline dynamicForm.php (3 of 12) Checks that all other form fields are filled in correctly Inserts a backslash before the parentheses in the phone number

80  2008 Pearson Education, Inc. All rights reserved. 80 Outline dynamicForm.php (4 of 12)

81  2008 Pearson Education, Inc. All rights reserved. 81 Outline dynamicForm.php (5 of 12) Ends script here if there were no errors in the user input Section to be executed only if $iserror is true

82  2008 Pearson Education, Inc. All rights reserved. 82 Outline dynamicForm.php (6 of 12) Alerts the user that there are errors Iterates through $inputlist to create the form’s text boxes Outputs the field’s image Sets the name attribute of the text field to $inputname Sets the value attribute of the text field to the value of the variable with the name of $inputname ’s value Puts an asterisk next to fields that have errors

83  2008 Pearson Education, Inc. All rights reserved. 83 Outline dynamicForm.php (7 of 12) Creates drop-down list for books, keeping the previously selected one selected

84  2008 Pearson Education, Inc. All rights reserved. 84 Outline dynamicForm.php (8 of 12) Creates radio buttons for operating-system selection, keeping the previously selected option selected

85  2008 Pearson Education, Inc. All rights reserved. 85 Outline dynamicForm.php (9 of 12)

86  2008 Pearson Education, Inc. All rights reserved. 86 Outline dynamicForm.php (10 of 12)

87  2008 Pearson Education, Inc. All rights reserved. 87 Outline dynamicForm.php (11 of 12)

88  2008 Pearson Education, Inc. All rights reserved. 88 Outline dynamicForm.php (12 of 12)

89  2008 Pearson Education, Inc. All rights reserved. 89 Outline formDatabase.php (1 of 3) Selects all fields from the contacts database to display

90  2008 Pearson Education, Inc. All rights reserved. 90 Outline formDatabase.php (2 of 3)

91  2008 Pearson Education, Inc. All rights reserved. 91 Outline formDatabase.php (3 of 3)

92  2008 Pearson Education, Inc. All rights reserved. 92 23.8 Operator Precedence Chart The following table contains a list of PHP operators in decreasing order of precedence.

93  2008 Pearson Education, Inc. All rights reserved. 93 Fig. 23.23 | PHP operator precedence and associativity. (Part 1 of 3.)

94  2008 Pearson Education, Inc. All rights reserved. 94 Fig. 23.23 | PHP operator precedence and associativity. (Part 2 of 3.)

95  2008 Pearson Education, Inc. All rights reserved. 95 Fig. 23.23 | PHP operator precedence and associativity. (Part 3 of 3.)


Download ppt " 2008 Pearson Education, Inc. All rights reserved. 1 23 PHP."

Similar presentations


Ads by Google