YOMEDIA
ADSENSE
PHP and MySQL by Example- P5
105
lượt xem 16
download
lượt xem 16
download
Download
Vui lòng tải xuống để xem tài liệu đầy đủ
Tham khảo tài liệu 'php and mysql by example- p5', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả
AMBIENT/
Chủ đề:
Bình luận(0) Đăng nhập để gửi bình luận!
Nội dung Text: PHP and MySQL by Example- P5
- Explanation 1 The HTML form is started here. Its action calls the script form.php. 2 The PHP script is started here. It will process the form input. 3 If the form has been submitted, the value $_POST['submit'] will be set. 4 The $_POST array contains the text that the user typed in the text area box, named story. (See Chapter 10, “More on PHP Forms,” for more information on the $_POST array.) For now, $input contains the input typed by the user. See Figure 6.36. 5 The stripslashes() function removes the slashes that were added by addslashes(), the default behavior when the magic_quotes_gpc directive has been turned on in the php.ini file. Figure 6.36. The user fills in a form. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Figure 6.37. After the form in Figure 6.36 is submitted. Output of Example 6.36. 6.2.15. Working with HTML Special Characters Like all languages, HTML has certain characters that have special significance and those characters are represented by HTML entities, special symbols starting with an ampersand and terminated with a semicolon; for example, the < and > symbols are written as < and >. If the user enters text that contains these HTML characters (see Table 6.14) when filling out a form, you can use the htmlspecialchars() function to convert the most common special characters to their respective HTML entities. If you require all HTML character entities to be translated, use htmlentities() shown in the next section. Table 6.14. HTML Special Character Functions Function What It Does htmlspecialchars_decode() Converts special HTML entities back to characters htmlspecialchars() Converts special characters to HTML entities The htmlspecialchars() Function The htmlspecialchars() function converts special characters (shown in Table 6.15) to HTML entities. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Table 6.15. Conversion of Special Characters Character Before The HTML Entity & (ampersand) & " (double quote) " when ENT_NOQUOTES is not set ' (single quote) ' only when ENT_QUOTES is set < (less than) < > (greater than) > Format string htmlspecialchars (string string [, int quote_style [, string charset]]) Example: $text = "Isn't the
- 2 echo "Original: $text"; 3 echo "Modified: ", htmlspecialchars($text), ""; ?> Explanation 1 The variable, $text, is assigned a string containing some characters considered special when rendered by the HTML interpreter; they are the < and & characters. 2 When this string is viewed in the browser, the HTML interpreter sees the < as an opening tag symbol followed by an irrelevant HTML element. Nothing is displayed other than the next opening < and the closing >. 3 The htmlspecialchars() function creates HTML entities out of the < and & so that the browser can display text. Note that the source page (see Figure 6.39) for the Web page shows that these entitities are now part of the page. Figure 6.38. Converting special characters to HTML entities. Output from Example 6.37. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Figure 6.39. Viewing the source page in the browser. The htmlentities() Function The htmlentities() function converts all applicable characters to their HTML entities equivalents. Format string htmlentities (string string [, int quote_style [, string charset]]) Example: $string = "5¢ won't get you much at the café Française!"; echo htmlentities($string, ENT_COMPAT); // Returns: 5¢ won't get you much at the cafè Française! Table 6.17. Supported Character Sets Charset Aliases Description ISO-‐8859-‐ ISO8859-‐1 Western European, Latin-‐1. 1 ISO-‐8859-‐ ISO8859-‐15 Western European, Latin-‐9. Adds the Euro sign, French 15 and Finnish letters missing in Latin-‐1 (ISO-‐8859-‐1). UTF-‐8 ASCII-‐compatible multibyte 8-‐bit Unicode. cp866 ibm866, 866 DOS-‐specific Cyrillic charset. This charset is supported in 4.3.2. cp1251 Windows-‐1251, Windows-‐specific Cyrillic charset. This charset is win-‐1251, 1251 supported in 4.3.2. cp1252 Windows-‐1252, Windows-‐specific charset for Western Europe. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Table 6.17. Supported Character Sets Charset Aliases Description 1252 KOI8-‐R koi8-‐ru, koi8r Russian. This charset is supported in 4.3.2. BIG5 950 Traditional Chinese, mainly used in Taiwan. GB2312 936 Simplified Chinese, national standard character set. BIG5-‐ Big5 with Hong Kong extensions, Traditional Chinese. HKSCS Shift_JIS SJIS, 932 Japanese. EUC-‐JP EUCJP Japanese. 6.3. Other String Functions This chapter focused on some of the most useful string functions, but PHP provides other useful string functions, as shown in Table 6.18. Table 6.18. PHP Functions Function What It Does addcslashes Quotes string with slashes in a C style. addslashes Quotes string with slashes. bin2hex Converts binary data into hexadecimal representation. chop Alias of rtrim(). chr Returns a specific character. chunk_split Splits a string into smaller chunks. convert_cyr_string Converts from one Cyrillic character set to another. convert_uudecode Decodes a uuencoded string. convert_uuencode Uuencodes a string. count_chars Returns information about characters used in a string. crc32 Calculates the crc32 polynomial of a string. crypt One-‐way string encryption (hashing). Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Table 6.18. PHP Functions Function What It Does echo Outputs one or more strings. explode Splits a string by string. fprintf Writes a formatted string to a stream. get_html_translation_table Returns the translation table used by htmlspecialchars() and htmlentities(). hebrev Converts logical Hebrew text to visual text. hebrevc Converts logical Hebrew text to visual text with newline conversion. html_entity_decode Converts all HTML entities to their applicable characters. htmlentities Converts all applicable characters to HTML entities. htmlspecialchars_decode Converts special HTML entities back to characters. htmlspecialchars Converts special characters to HTML entities. implode Joins array elements with a string. join Alias of implode(). levenshtein Calculates Levenshtein distance between two strings. localeconv Gets numeric formatting information. ltrim Strips whitespace (or other characters) from the beginning of a string. md5_file Calculates the md5 hash of a given file. md5 Calculates the md5 hash of a string. metaphone Calculates the metaphone key of a string. money_format Formats a number as a currency string. nl_langinfo Query language and locale information. nl2br Inserts HTML line breaks before all newlines in a string. number_format Formats a number with grouped thousands. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Table 6.18. PHP Functions Function What It Does ord Returns ASCII value of character. parse_str Parses the string into variables. print Outputs a string. printf Outputs a formatted string. quoted_printable_decode Converts a quoted-‐printable string to an 8-‐bit string. quotemeta Quotes metacharacters. rtrim Strips whitespace (or other characters) from the end of a string. setlocale Sets locale information. sha1_file Calculates the sha1 hash of a file. sha1 Calculates the sha1 hash of a string. similar_text Calculates the similarity between two strings. soundex Calculates the soundex key of a string. sprintf Returns a formatted string. sscanf Parses input from a string according to a format. str_ireplace Case-‐insensitive version of str_replace(). str_pad Pads a string to a certain length with another string. str_repeat Repeats a string. str_replace Replaces all occurrences of the search string with the replacement string. str_rot13 Performs the rot13 encoding on a string. Shifts every alpha character 13 places in the alphabet. str_shuffle Randomly shuffles a string. str_split Converts a string to an array. str_word_count Returns information about words used in a string. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Table 6.18. PHP Functions Function What It Does strcasecmp Binary-‐safe case-‐insensitive string comparison. strchr Alias of strstr(). strcmp Binary-‐safe string comparison. strcoll Locale-‐based string comparison. strcspn Finds length of initial segment not matching mask. strip_tags Strips HTML and PHP tags from a string. stripcslashes Unquotes string quoted with addcslashes(). stripos Finds position of first occurrence of a case-‐insensitive string. stripslashes Unquotes string quoted with addslashes(). stristr Case-‐insensitive strstr(). strlen Gets string length. strnatcasecmp Case-‐insensitive string comparisons using a “natural order” algorithm. strnatcmp String comparisons using a “natural order” algorithm. strncasecmp Binary-‐safe case-‐insensitive string comparison of the first n characters. strncmp Binary-‐safe string comparison of the first n characters. strpbrk Searches a string for any of a set of characters. strpos Finds position of first occurrence of a string. strrchr Finds the last occurrence of a character in a string. strrev Reverses a string. strripos Finds position of last occurrence of a case-‐insensitive string in a string. strrpos Finds position of last occurrence of a character in a string. strspn Finds length of initial segment matching mask. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Table 6.18. PHP Functions Function What It Does strstr Finds first occurrence of a string. strtok Tokenizes string. strtolower Makes a string lowercase. strtoupper Makes a string uppercase. strtr Translates certain characters. substr_compare Binary-‐safe optionally case-‐insensitive comparison of two strings from an offset, up to length characters. substr_count Counts the number of substring occurrences. substr_replace Replaces text within a portion of a string. substr Returns part of a string. trim Strips whitespace (or other characters) from the beginning and end of a string. ucfirst Makes a string’s first character uppercase. ucwords Uppercases the first character of each word in a string. vfprintf Writes a formatted string to a stream. vprintf Outputs a formatted string. vsprintf Returns a formatted string. wordwrap Wraps a string to a given number of characters using a string break character. 6.4. Chapter Summary 6.4.1. What You Should Know Now that you have finished this chapter you should be able to answer the following questions: 1. What is a string? 2. When do you use double quotes or single quotes? 3. What are escape characters? Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- 4. Define whitespace. 5. What functions let you format strings? 6. How can you get the length of a string and count the characters in a substring? 7. What functions compare strings? Are strings case sensitive when they are compared? 8. What functions find similarities in strings? 9. How do you find a position in a string? What functions let you find a specified position in a string? 10. What is a substring? What functions extract parts of a string? 11. What is meant by “trimming” and “padding”? 12. What functions are used for searching and replacing within strings? 13. What are special characters? 14. What are HTML entities? 15. How do you force breaks in a string? 16. What functions deal with homophones? 6.4.2. What’s Next? Chapter 7, “Conditionals and Loops,” covers PHP conditional statements (if/else/elseif, switch) and loops (while, for, foreach). Chapter 6 Lab 1. Assign your e-‐mail address to a string. Use PHP string functions to get the user name and the domain name. 2. Create the following string: $string = " mary jones lives in santa cruz, california at 22 ocean drive." a. Find the number of characters in the string. b. Capitalize all the letters in the string. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- c. Now make all the characters lowercase. d. Use the substr() function to print Santa Cruz, California. The first letter in each word will be in uppercase. e. Use the substr() function to print Mary’s street address. f. Trim out the whitespace at the beginning of the string. g. Find the index position of California. h. Replace Santa Cruz with Los Altos (case insensitive). i. Find the number of words in the string. 3. Use the strcmp() function to compare the following two strings, first comparing $str1 and $str2, then comparing $str2 and $str1. Explain the value that is returned from the function. $str1="Pear"; $str2="Pearson"; What value is returned from strcmp() if you compare $str1 to $str1? 4. Write a script to generate a 4-‐letter random password with uppercase, lowercase, and numeric characters. Store the password as a variable and display it.Start with: $str = "abcdefghijklmnopqrlsuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Hint: Try str_shuffle(). 5. Create a scalar variable to contain a money amount of 155000000. Use the number_format() function to display the number as U.S. dollars with a comma separator and decimal point. Now display the same number in Euros as it would be formatted in Western Europe and place the Euro symbol before the number (€). Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Chapter 7. Conditionals and Loops 7.1. Control Structures, Blocks, and Compound Statements Figure 7.1 shows a flow chart. A flow chart is defined as a pictorial representation of how to plan the stages of a project. It helps to visualize what decisions need to be made to accomplish a task. People control their lives by making decisions, and so do programs. In fact, acccording to computer science books, a good language allows you to control the flow of your program in three ways: • Execute a sequence of statements. • Based on a test, branch to an alternative sequence of statements. • Repeat a sequence of statements until some condition is met. Figure 7.1. A flow chart. Well, then, PHP must be a good language. We’ve already used programs that execute a sequence of statements, one after another. Now we examine the branching and looping control structures that allow the flow of the program’s control to change depending on some conditional expression. The decision-making constructs (if, if/else, if/else if) contain a control expression that determines whether a block of statements will be executed. The looping constructs (while, for) allow the program to repetitively execute a statement block until some condition is satisfied. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- A compound statement or block consists of a statement or a group of statements surrounded by curly braces. The block is syntactically equivalent to a single statement and usually follows an if, else, while, or for construct. This is a block: { statement; statement; statement } 7.1.1. Conditionals Conditional constructs control the flow of a program. If a condition is true, the program will execute a block of statements and if the condition is false, flow will go to an alternate block of statements. Decision-making constructs (if, else, switch) contain a control expression that determines whether or not a block of expressions will be executed. If the condition after the if is met, the result is true, and the following block of statements is executed; otherwise, the result is false and the block is not executed. Format if (condition){ statements; } Example: if ( $age > 21 ){ print "Let's Party!"; } The block of statements (or single statement) is enclosed in curly braces. Normally statements are executed sequentially. If there is only one statement after the conditional expression, the curly braces are optional. if/else “You better pay me now, or else . . .” Have you heard that kind of English statement before? PHP statements can be handled the same way with the if/else branching construct. This construct allows for a two-way decision. The if evaluates the first conditional expression in parentheses, and if the expression evaluates to true, the block after the opening curly braces is executed; otherwise, the block after the else is executed. The else is optional. See Example 7.1. Format if (condition){ statements1; } else{ statements2; } Example: if ( $x > $y ){ print "$x is larger"; } else{ print "y is larger"; } Example 7.1. Code View: (The HTML Form) Your Fare How old are you? ------------------------------------------------------------------ (The PHP Script) Your Fare Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Explanation 1 If the variable has not been set, the program will exit. 2– If the value of the variable $age is greater than or equal to 55, lines 3 and 4 are 4 executed. See Figures 7.2 and 7.3. 5 This closing curly brace closes the block of statements following the if expression. Because there is only one statement in the block, the curly braces are not required. 6– The else statements, lines 7 and 8, are executed if the expression in line 2 is false. 8 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Figure 7.2. The HTML form from Example 7.1. Figure 7.3. After the user presses the “Get Fare” button to submit the form. Output of the PHP script from Example 7.1. if/elseif If you’ve got $1, we can go to the Dollar Store, else if you’ve got $10, we could get a couple of movies, else if you’ve got $20 we could buy a CD . . . or else forget it!” PHP provides yet another form of branching, the if/elseif construct. This construct provides a multiway decision structure. Format if (condition) { statements1; } elseif (condition) { statements2; } elseif (condition) { statements3; } else{ statements4; } If the first conditional expression following the if keyword is true, the statement or block of statements following the expression are executed and control starts after the else block. Otherwise, if the conditional expression following the if keyword is false, control branches to the first elseif and the expression following it is evaluated. If that expression is true, the statement or block of statements following it are executed, and if false, the next elseif is tested. All else ifs are tested and if none of their expressions are true, control goes to the else statement. Although the else is not required, it normally serves as a default action if all previous conditions were false. See Example 7.2 for if/elseif construct. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Example 7.2. Code View: (The HTML Form) Your Movie Fare
- 10 ?> Explanation 1 The HTML form starts here. The action attribute is assigned the name of the PHP script that will be executed after the form is submitted. 2 The text box is named "age" and will be sized to hold three characters. 3 The HTML submit input type is given a name, submit_fare, that will be used in the following PHP script. 4 The opening PHP tag tells PHP to start processing. 5 Now we are looking at the PHP instructions. If the user pressed the submit button, this file will execute. PHP will store the names of the input devices in variables, $age and $submit_fare. This conditional expression tests to see if those variables were set. If they weren’t set, then the form was either not submitted or the user left it empty, or both. 6 If is true that the user’s age is greater than 0 and also less than 13, the block that follows the expression will be executed. As soon as the block is executed, the program will start execution on line 10. If the expression evaluates to false, then the program will go to line 7. 7 If the condition on line 6 is false, the program checks the conditional expression after the elseif, and if it is true (i.e., the age is greater than or equal to 13 and less than 55), the block of statements will be executed. Otherwise, the program will go to line 8. 8 If the conditional test in line 7 is false, this elseif condition will be checked, and if true, the block of statements following it will be executed. If false, the block of statements after the else on line 9 are executed. 9 If none of the preceding conditions are met, control goes to the else block, often called the default condition, and the statements in its block are executed. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Figure 7.4. The HTML form from Example 7.2. Figure 7.5. The PHP output from Example 7.2. The switch Statement The switch statement is an alternative to the if/elseif conditional construct, commonly called a a case statement, and often makes the program more readable when handling multiple options. Format switch (expression){ case label : statement(s); break; case label : statement(s); break; ... default : statement; } Example: switch ($color){ case "red": print "Hot!"; break; case "blue": print "Cold."; break; default: print "Not a good choice."; break; } The value of the switch expression is matched against the expressions, called labels, following the case keyword. The case labels are constants, either string or numeric. Each label is terminated with a colon. The default label is optional, but its action is taken if none of the other cases match the switch expression. After a match is found, the statements after the matched label are executed for that case. If none of the cases are matched, the control drops to the default case. The default is optional. If a break statement is omitted, all statements below the matched label are executed until either a break is reached or the entire switch block exits. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Example 7.3. Code View: (The HTML File) Pick a Font Color Choose a font color: red blue purple green ------------------------------------------------------------------ (The PHP Script) Font Color 1 3
ADSENSE
CÓ THỂ BẠN MUỐN DOWNLOAD
Thêm tài liệu vào bộ sưu tập có sẵn:
Báo xấu
LAVA
AANETWORK
TRỢ GIÚP
HỖ TRỢ KHÁCH HÀNG
Chịu trách nhiệm nội dung:
Nguyễn Công Hà - Giám đốc Công ty TNHH TÀI LIỆU TRỰC TUYẾN VI NA
LIÊN HỆ
Địa chỉ: P402, 54A Nơ Trang Long, Phường 14, Q.Bình Thạnh, TP.HCM
Hotline: 093 303 0098
Email: support@tailieu.vn