Presentation is loading. Please wait.

Presentation is loading. Please wait.

Jozef Goetz contribution, 2011 1 Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice.

Similar presentations


Presentation on theme: "Jozef Goetz contribution, 2011 1 Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice."— Presentation transcript:

1

2 Jozef Goetz contribution, 2011 1 Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall

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

4 Jozef Goetz contribution, 2011 3  Reckoners without their host must reckon twice.  John Heywood  There was a door to which I found no key; There was the veil through which I might not see.  Omar Khayyam

5 Jozef Goetz contribution, 2011 4 OBJECTIVES In this chapter you will learn:  To manipulate data of various types.  To use operators, arrays and control statements.  To use regular expressions to search for patterns.  To construct programs that process form data.  To store data on the client using cookies.  To create programs that interact with MySQL databases.

6 Jozef Goetz contribution, 2011 5  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 Jozef Goetz contribution, 2011 6 23.1 Introduction  PHP, or PHP: Hypertext Preprocessor, has become one of the most popular server-side scripting languages for creating dynamic web pages.  PHP is open source and platform independent— implementations exist for all major UNIX, Linux, Mac and Windows operating systems.  PHP also supports a large number of databases.

8 Jozef Goetz contribution, 2011 PHP was rated the best scripting language  The survey asked more than 500 developers to rate the scripting languages they use according to features and capabilities such as (http://www.infoq.com/news/2009/03/top-scripting-languages-php-ruby) :http://www.infoq.com/news/2009/03/top-scripting-languages-php-ruby  ease of use,  exception handling,  extensibility,  maintainability/readability,  cross-platform portability,  community,  availability of tools,  quality of tools,  performance,  memory management,  client-side scripting, and security.  Languages in the survey included: Actionscript, Flex, Java Script, F#, Windows Powershell, Perl, PHP, Python, Ruby, and VB Script  The study concluded that PHP was the best all-around scripting language for web applications with a large community and lots of readily available tools. 7

9 Jozef Goetz contribution, 2011 PHP most popular scripting language  From PHP for theWeb ed 4 by Larry Ullman (2011) p Xiii:  PHP is most popular tool available for developing dynamic Web sites  PHP is in use on over 75% of all Web sites (Jan 2011) and it is the fourth most popular programming language overall  PHP can do certain task faster and more easily than the alternatives  open source nature means that PHP’s users are driving its development, not some corporate entity  PHP is used by:  the biggest web sites Yahoo!, Wikipedia, Facebook,  content management tools: WordPress, Drupal, Moodle, and Joomla  By learning you’ll provide yourself with either a usable hobby or a lucrative skill 8

10 Jozef Goetz contribution, 2011 9 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.

11 Jozef Goetz contribution, 2011 10 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.

12 Jozef Goetz contribution, 2011 11 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

13 Jozef Goetz contribution, 2011 12 Common Programming Error 23.1  Failing to precede a variable name with a $ is a syntax error.

14 Jozef Goetz contribution, 2011 13 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.

15 Jozef Goetz contribution, 2011 14 Common Programming Error 23.3  Forgetting to terminate a statement with a semicolon ( ; ) is a syntax error.

16 Jozef Goetz contribution, 2011 15 Fig. 23.2 | PHP types.

17 Jozef Goetz contribution, 2011 16 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.

18 Jozef Goetz contribution, 2011 17 Outline data.php (1 of 3) Automatically declares a string Automatically declares a double Automatically declares an integer Outputs the type of $testString

19 Jozef Goetz contribution, 2011 18 Outline data.php (2 of 3) Modifies $testString to be a double Modifies $testString to be an integer Modifies $testString to be a string

20 Jozef Goetz contribution, 2011 19 Outline data.php (3 of 3) Temporarily casts $data as a double and an integer Concatenation

21 Jozef Goetz contribution, 2011 20 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.

22 Jozef Goetz contribution, 2011 21 23.2 PHP Basics (Cont.)  Function define creates a named constant.  It takes two arguments—the name and value of the constant. Line 17 of Fig.23.4  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.

23 Jozef Goetz contribution, 2011 22 Common Programming Error 23.4  Assigning a value to a constant after it is declared is a syntax error.

24 Jozef Goetz contribution, 2011 23 Outline operators.php (1 of 3) Creates the named constant VALUE with a value of 5 Equivalent to $a = $a * 2

25 Jozef Goetz contribution, 2011 24 Outline operators.php (2 of 3) Uses a comparison operator with a variable and an integer Uninitialized variable $num evaluates to 0

26 Jozef Goetz contribution, 2011 25 Outline operators.php (3 of 3) $str is converted to an integer for this operation

27 Jozef Goetz contribution, 2011 26 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.

28 Jozef Goetz contribution, 2011 27 Fig. 23.5 | PHP keywords.

29 Jozef Goetz contribution, 2011 28 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.

30 Jozef Goetz contribution, 2011 29 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.) foreach ( $fourth as $element => $value ) print( "$element is the $value month " );

31 Jozef Goetz contribution, 2011 30 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

32 Jozef Goetz contribution, 2011 31 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; When function cannot return an index => $element = false Moves the internal pointer to the next element and returns it; returns false when there are no more elements in the array

33 Jozef Goetz contribution, 2011 32 Outline 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

34 Jozef Goetz contribution, 2011 33 Outline arrays.php (4 of 4)

35 Jozef Goetz contribution, 2011 34 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.

36 Jozef Goetz contribution, 2011 35 Outline compare.php (1 of 2) Checks whether the ith element of the fruits array preceeds the string banana

37 Jozef Goetz contribution, 2011 36 Outline compare.php (2 of 2) Uses relational operators to compare the element of the fruits array with the string apple

38 Jozef Goetz contribution, 2011 37 23.3 String Processing and Regular Expressions (Cont.)  Goal: find pattern in text  Regular expression (as ereg ) – specially formated strings used to find patterns in text  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 first string- which evaluates to true in a boolean context.  Function ereg receives a regular expression pattern to search for and the string to search.  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.  Function eregi performs case-insensitive pattern matches.  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.

39 Jozef Goetz contribution, 2011 38 23.3 String Processing and Regular Expressions (Cont.)  Anything enclosed in single quotes in a print statement is not interpolated (unless the single quotes are nested in a double-quoted string literal).  Regular expressions can include metacharacters that specify patterns.  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 ( - ). ex: [a-zA-Z]  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.

40 Jozef Goetz contribution, 2011 39 23.3 String Processing and Regular Expressions (Cont.)  A character class represents a group of characters that might appear in a string ex. [[:alpha:]]  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 3 arguments— the pattern to match, a string to replace the matched string and the string to search.  The modified string is returned.

41 Jozef Goetz contribution, 2011 40 Fig. 23.9 | Some PHP quantifiers.

42 Jozef Goetz contribution, 2011 41 Fig. 23.10 | Some PHP character classes.

43 Jozef Goetz contribution, 2011 42 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

44 Jozef Goetz contribution, 2011 43 Outline expression.php (2 of 2) Searches for a word ending in “ow” and stores matches in $match array Quantifier * matches the preceding pattern 0 or more times $match[0] stores the string matches for the entire pattern Prints first $match[1] encountered instance of word ending in “ow”; Second encountered instance of word ending in “ow” will be in $match[2] Performs a case-insensitive search for words beginning with the letter “t” and then [[:alpha:]]+ i.e. [a-zA-Z]). 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 Function ereg_replace takes 3 arguments the pattern to match, a string to replace the matched string and the string to search. The modified string is returned.

45 Jozef Goetz contribution, 2011 44 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.

46 Jozef Goetz contribution, 2011 45 Fig. 23.11 | Some useful superglobal arrays.

47 Jozef Goetz contribution, 2011 46 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

48 Jozef Goetz contribution, 2011 47 Outline form.html (2 of 4) Creates form fields Creates drop-down list with book names

49 Jozef Goetz contribution, 2011 48 Outline form.html (3 of 4) Creates radio buttons with “Windows XP” initially selected

50 Jozef Goetz contribution, 2011 49 Outline form.html (4 of 4)

51 Jozef Goetz contribution, 2011 50 Good Programming Practice 23.1  Use meaningful XHTML object names for input fields.  This makes PHP scripts that retrieve form data easier to understand.

52 Jozef Goetz contribution, 2011 51 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.

53 Jozef Goetz contribution, 2011 52 Outline form.php (1 of 5)

54 Jozef Goetz contribution, 2011 53 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

55 Jozef Goetz contribution, 2011 54 Outline form.php (3 of 5) Prints the value entered in the email field in form.html

56 Jozef Goetz contribution, 2011 55 Outline form.php (4 of 5)

57 Jozef Goetz contribution, 2011 56 Outline form.php (5 of 5)

58 Jozef Goetz contribution, 2011 57 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.

59 Jozef Goetz contribution, 2011 58 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(" ").

60 Jozef Goetz contribution, 2011 59 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.

61 Jozef Goetz contribution, 2011 60 Outline data.html (1 of 2) Posts data to database.php

62 Jozef Goetz contribution, 2011 61 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

63 Jozef Goetz contribution, 2011 62 Outline database.php (1 of 3) Builds a SELECT query with the selection made in data.html

64 Jozef Goetz contribution, 2011 63 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

65 Jozef Goetz contribution, 2011 64 Outline database.php (3 of 3) "$counter“ has the # of rows; The same as mysql_num_rows($result)

66 Jozef Goetz contribution, 2011 65 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.

67 Jozef Goetz contribution, 2011 66 Outline cookies.html (1 of 2) Posts form data to cookies.php Creates fields to gather information to be written into a cookie

68 Jozef Goetz contribution, 2011 67 Outline cookies.html (2 of 2) Form field

69 Jozef Goetz contribution, 2011 68 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

70 Jozef Goetz contribution, 2011 69 Outline cookies.php (2 of 2) Links to the page that displays the contents of the cookie

71 Jozef Goetz contribution, 2011 70 Software Engineering Observation 23.2 - 3  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.  Cookies should not be used to store e-mail addresses or private data on a client’s computer.

72 Jozef Goetz contribution, 2011 71 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.

73 Jozef Goetz contribution, 2011 72 Fig. 23.18 | IE7’s Cookies directory before a cookie is written. Fig. 23.19 | IE7’s Cookies directory after a cookie is written.

74 Jozef Goetz contribution, 2011 73 23.6 Using Cookies (Cont.)  PHP creates the superglobal array $_COOKIE, which contains all the cookie values indexed by their names.

75 Jozef Goetz contribution, 2011 74 Outline readCookies.php (1 of 2)

76 Jozef Goetz contribution, 2011 75 Outline readCookies.php (2 of 2) Iterates through all values in $_COOKIE

77 Jozef Goetz contribution, 2011 76 23.7 Dynamic Content  Function isset allows you to find out if a variable has a value.  A 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.

78 Jozef Goetz contribution, 2011 77 Outline dynamicForm.php (1 of 12)

79 Jozef Goetz contribution, 2011 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

80 Jozef Goetz contribution, 2011 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

81 Jozef Goetz contribution, 2011 80 Outline dynamicForm.php (4 of 12)

82 Jozef Goetz contribution, 2011 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

83 Jozef Goetz contribution, 2011 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

84 Jozef Goetz contribution, 2011 83 Outline dynamicForm.php (7 of 12) Creates drop-down list for books, keeping the previously selected one selected

85 Jozef Goetz contribution, 2011 84 Outline dynamicForm.php (8 of 12) Creates radio buttons for operating-system selection, keeping the previously selected option selected

86 Jozef Goetz contribution, 2011 85 Outline dynamicForm.php (9 of 12)

87 Jozef Goetz contribution, 2011 86 Outline dynamicForm.php (10 of 12)

88 Jozef Goetz contribution, 2011 87 Outline dynamicForm.php (11 of 12)

89 Jozef Goetz contribution, 2011 88 Outline dynamicForm.php (12 of 12)

90 Jozef Goetz contribution, 2011 89 Outline formDatabase.php (1 of 3) Selects all fields from the contacts database to display

91 Jozef Goetz contribution, 2011 90 Outline formDatabase.php (2 of 3)

92 Jozef Goetz contribution, 2011 91 Outline formDatabase.php (3 of 3)

93 Jozef Goetz contribution, 2011 92 23.8 Operator Precedence Chart  The following table contains a list of PHP operators in decreasing order of precedence.

94 Jozef Goetz contribution, 2011 93 Fig. 23.23 | PHP operator precedence and associativity. (Part 1 of 3.)

95 Jozef Goetz contribution, 2011 94 Fig. 23.23 | PHP operator precedence and associativity. (Part 2 of 3.)

96 Jozef Goetz contribution, 2011 95 Fig. 23.23 | PHP operator precedence and associativity. (Part 3 of 3.)


Download ppt "Jozef Goetz contribution, 2011 1 Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice."

Similar presentations


Ads by Google