1 / 95

Chapter 23 PHP Part I

Chapter 23 PHP Part I. Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall. Conversion for me was not a Damascus Road experience. I slowly moved into a intellectual acceptance of what my intuition had always known.

trung
Download Presentation

Chapter 23 PHP Part I

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 23 PHP Part I Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall

  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

  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

  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.

  5. 23.1 Introduction • 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

  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.

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

  8. PHP most popular scripting language • From PHP for theWebed 4 by Larry Ullman (2011) p Xiii: • PHP is most popular tool availablefor 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 certaintask 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

  9. 23.2 PHP Basics • The power of the web resides not only in servingcontent 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 and ?>. • PHP code can be placed anywhere in XHTML markup, as long as the code is enclosed in these delimiters.

  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 thevariable’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.

  11. Outline Delimiters enclosing PHP script first.php Declares and initializes a PHP variable Interpolates the variable so that its value will be output to the XHTML document

  12. Common Programming Error 23.1 • Failing to precede a variable namewith a $ is a syntax error.

  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.

  14. Common Programming Error 23.3 • Forgetting to terminate a statementwith a semicolon (;) is a syntax error.

  15. Fig. 23.2 | PHP types.

  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.

  17. Outline data.php (1 of 3) Automatically declares a string Automatically declares a double Automatically declares an integer Outputs the type of $testString

  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

  19. Outline Temporarily casts $data as a double and an integer data.php (3 of 3) Concatenation

  20. Error-Prevention Tip 23.1 • Function print can be used to displaythe value of a variable at a particularpoint during a program’s execution. • This is often helpful in debugging a script.

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

  22. Common Programming Error 23.4 • Assigning a value to a constant afterit is declared is a syntax error.

  23. Outline operators.php (1 of 3) Creates the named constantVALUE with a value of 5 Equivalent to $a = $a * 2

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

  25. Outline $str is converted to an integer for this operation operators.php (3 of 3)

  26. Error-Prevention Tip 23.2 • Initialize variables before they are usedto avoid subtle errors. • For example, multiplying a number by an uninitialized variable results in 0.

  27. Fig. 23.5 | PHP keywords.

  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 appendsa new element to the endof the array. • Functioncount returns the total number of elements in the array. • Functionarray creates an array that contains the arguments passed to it. • The first item in the argument list is stored as the first array element (index0), the second item is stored as the second array element and so on.

  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 indexand 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 indexof 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 <br />" );

  30. Outline arrays.php (1 of 4) Automatically creates array $first Sets the first element of array $first to the string “zero” “three” is appended to the end of array $first Returns the number of elements in the array

  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

  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

  33. Outline arrays.php (4 of 4)

  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.

  35. Outline compare.php (1 of 2) Checks whether the ith element of the fruits array preceeds the string banana

  36. Outline compare.php (2 of 2) Uses relational operators to compare the element of the fruits array with the string apple

  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.

  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 [[:<:]] and [[:>:]]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.

  39. 23.3 String Processing and Regular Expressions (Cont.) • A character classrepresents 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 classesin 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.

  40. Fig. 23.9 | Some PHP quantifiers.

  41. Fig. 23.10 | Some PHP character classes.

  42. Outline 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 expression.php (1 of 2)

  43. Outline Searches for a word ending in “ow” and stores matches in $match array Quantifier * matches the preceding pattern 0 or more times expression.php (2 of 2) $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]). • 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. 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

  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 $_POSTretrieve 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.

  45. Fig. 23.11 | Some useful superglobal arrays.

  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

  47. Outline form.html (2 of 4) Creates form fields Creates drop-down list with book names

  48. Outline form.html (3 of 4) Creates radio buttons with “Windows XP” initially selected

  49. Outline form.html (4 of 4)

  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.

More Related