# PHP & MySQL for Dummies- P4

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

0
75
lượt xem
12

## PHP & MySQL for Dummies- P4

Mô tả tài liệu

Tham khảo tài liệu 'php & mysql for dummies- p4', công nghệ thông tin, cơ sở dữ liệu phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả

Chủ đề:

Bình luận(0)

Lưu

## Nội dung Text: PHP & MySQL for Dummies- P4

1. Part III PHP Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
2. In this part . . . I n Part III, you find out how to use PHP for your Web database application. Here are some of the topics described: U Adding PHP to HTML files U PHP features that are useful for building a dynamic Web database application U Using PHP features U Using forms to collect information from users U Showing information from a database in a Web page U Storing data in a database U Moving information from one Web page to the next You find out everything you need to know to write PHP programs. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
6. 136 Part III: PHP In this PHP program, the PHP section is The PHP tags enclose only one statement — an echo statement. The echo statement is a PHP statement that you’ll use frequently. It simply outputs the text that is included between the double quotes. There is no rule that says you must enter the PHP on separate lines. You could just as well include the PHP in the file on a single line, like this: When the PHP section is processed, it is replaced with the output. In this case, the output is Hello World! If you replace the PHP section in Listing 6-2 with the preceding output, the program now looks exactly like the HTML program in Listing 6-1. If you point your browser at either program, you see the same Web page. If you look at the source code that the browser sees (in the browser, choose View➪Source), you see the same source code listing for both programs. Writing PHP Statements The PHP section that you add to your HTML file consists of a series of PHP statements. Each PHP statement is an instruction to PHP to do something. In the Hello World program shown in Listing 6-2, the PHP section contains only one simple PHP statement. The echo statement instructs PHP to output the text between the double quotes. PHP statements end with a semicolon (;). PHP does not notice white space or the ends of lines. It continues reading a statement until it encounters a semicolon or the PHP closing tag, no matter how many lines the statement spans. Leaving out the semicolon is a common error, resulting in an error message that looks something like this: Parse error: expecting ’,’’ or ’;’’ in /hello.php on line 6 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
9. Chapter 6: General PHP 139 error_reporting = E_ALL | E_STRICT error_reporting = 0 error_reporting = E_ALL & ~ E_NOTICE The first setting is best, because it displays everything. It displays E_ALL, which is all errors, warnings, and notices except strict, and E_STRICT, which displays strict messages. The second setting displays no error messages. The third setting displays all error and warning messages, but not notices or stricts. After changing the error_reporting settings, save the edited php. ini file and restart your Web server. If you’re using a local php.ini file on your Web host, just add a statement, like one of the preced- ing statements, to your local php.ini file. If you don’t have access to php.ini, you can add a statement to a program that sets the error reporting level for that program only. Add the following statement at the beginning of the program: error_reporting(errorSetting); For example, to see all errors except stricts, use the following: error_reporting(E_ALL); You may want to put this statement in the top of your scripts when you run them on your Web host. Then, when your programs are working perfectly and your Web site is ready for visitors, you can remove the statement from the scripts. In addition, PHP provides a setting that determines whether errors are displayed on the Web page at all. This setting in your php.ini file is: display_errors = On You can change this to Off in a php.ini file or add the following statement to the top of your script: ini_set(“display_errors”,”Off”); Using PHP Variables Variables are containers used to hold information. A variable has a name, and information is stored in the variable. For instance, you might name a variable $age and store the number 12 in it. After information is stored in a variable, it can be used later in the program. One of the most common uses for vari- ables is to hold the information that a user types into a form. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 10. 140 Part III: PHP Naming a variable When you’re naming a variable, keep the following rules in mind: ✓ All variable names have a dollar sign ($) in front of them. This tells PHP that it is a variable name. ✓ Variable names can be any length. ✓ Variable names can include letters, numbers, and underscores only. ✓ Variable names must begin with a letter or an underscore. They cannot begin with a number. ✓ Uppercase and lowercase letters are not the same. For example, $firstname and$Firstname are not the same variable. If you store information in $firstname, for example, you can’t access that informa- tion by using the variable name$firstName. When you name variables, use names that make it clear what information is in the variable. Using variable names like $var1,$var2, $A, or$B does not contribute to the clarity of the program. Although PHP doesn’t care what you name the variable and won’t get mixed up, people trying to follow the program will have a hard time keeping track of which variable holds what information. Variable names like $firstName,$age, and $orderTotal are much more descriptive and helpful. Creating and assigning values to variables Variables can hold either numbers or strings of characters. You store infor- mation in variables by using a single equal sign (=). For instance, the follow- ing four PHP statements assign information to variables:$age = 12; $price = 2.55;$number = -2; $name = “Goliath Smith”; Notice that the character string is enclosed in quotes, but the numbers are not. I provide details about using numbers and characters later in this chap- ter, in the “Working with Numbers” and “Working with Character Strings” sections. You can now use any of these variable names in an echo statement. For instance, if you use the following PHP statement in a PHP section: echo$age; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
11. Chapter 6: General PHP 141 the output is 12. If you include the following line in an HTML file: Your age is . the output on the Web page is Your age is 12. Whenever you put information into a variable that did not exist before, you create that variable. For instance, suppose you use the following PHP statement: $firstname = “George”; If this statement is the first time that you’ve mentioned the variable$first name, this statement creates the variable and sets it to “George”. If you have a previous statement setting $firstname to “Mary”, this statement changes the value of$firstname to “George”. You can also remove information from a variable. For example, the following statement takes information out of the variable $age:$age = “”; The variable $age exists but does not contain a value. It does not mean that$age is set to 0 (zero) because 0 is a value. It means that $age does not store any information. It contains a string of length 0. You can go even further and uncreate the variable by using this statement: unset($age); After this statement is executed, the variable $age no longer exists. A variable keeps its information for the entire program, not just for a single PHP section. If a variable is set to “yes” at the beginning of a file, it still holds “yes” at the end of the page. For instance, suppose your file has the following statements: Hello World! Hello World again! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 12. 142 Part III: PHP The echo statement in the second PHP section displays Harry. The Web page resulting from these statements is Hello World! Hello World again! Harry Dealing with notices If you use a statement that includes a variable that does not exist, you might get a notice. It depends on the error-message level that PHP is set to. Remember that notices aren’t the same as error messages. With a notice, the program continues to run. A notice simply tells you that you’re doing something unusual and to take a second look at what you’re doing. (See the sidebar, “Error messages and warnings.”) For instance, suppose you use the following statements: unset($age); echo $age;$age2 = $age; You might see two notices: one for the second statement and one for the third statement. The notices will look something like this: Notice: Undefined variable: age in testing.php on line 9 Suppose that you definitely want to use these statements. The program works exactly the way you want it to. The only problems are the unsightly notices. You can prevent notices in a program by inserting an at sign (@) at the point where the notice would be issued. For instance, you can prevent the notices generated by the preceding statements if you change the state- ments to this: unset($age); echo @$age;$age2 = @$age; Using PHP Constants PHP constants are similar to variables. Constants are given a name, and a value is stored in them. However, constants are constant; that is, they can’t be changed by the program. After you set the value for a constant, it stays Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 13. Chapter 6: General PHP 143 the same. If you used a constant for age and set it to 29, for example, it can’t be changed. Wouldn’t that be nice — 29 forever? Constants are used when a value is needed several places in the program and doesn’t change during the program. The value is set in a constant at the start of the program. By using a constant throughout the program, instead of a variable, you make sure that the value won’t get changed accidentally. By giving it a meaningful name, you know what the information is instantly. And by setting a constant once at the start of the program (instead of using the value throughout the program), you can change the value in one place if it needs changing, instead of hunting for it in many places in the program to change it. For instance, you might set one constant that’s the company name and another constant that’s the company address and use them wherever needed. Then, if the company moves, you could just change the value in the company address at the start of the program instead of having to find every place in your program that echoed the company name to change it. You can set a constant by using the define statement. The format is define(“constantname”,”constantvalue”); For instance, to set a constant with the company name, use the following statement: define(“COMPANY”,”ABC Pet Store”); Use the constant in your program wherever you need your company name: echo COMPANY; When you echo a constant, you can’t enclose it in quotes. If you do, it echoes the constant name, instead of the value. You can echo it without anything, as shown in the preceding example, or enclosed with parentheses. You can use any name for a constant that you can use for a variable. Constant names are not preceded by a dollar sign ($). By convention, con- stants are given names that are all uppercase, so you can easily spot con- stants, but PHP itself doesn’t care what you name a constant. You can store either a string or a number in it. The following statement is perfectly okay with PHP: define(“AGE”,29); Just don’t expect Mother Nature to believe it. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
14. 144 Part III: PHP Working with Numbers PHP allows you to do arithmetic operations on numbers. You indicate arith- metic operations with two numbers and an arithmetic operator. For instance, one operator is the plus (+) sign, so you can indicate an arithmetic operation like this: 1 + 2 You can also perform arithmetic operations with variables that contain num- bers, as follows: $n1 = 1;$n2 = 2; $sum =$n1 + $n2; Table 6-1 shows the arithmetic operators that you can use. Table 6-1 Arithmetic Operators Operator Description + Add two numbers. - Subtract the second number from the first number. * Multiply two numbers. / Divide the first number by the second number. % Find the remainder when the first number is divided by the second number. This is called modulus. For instance, in$a = 13 % 4, $a is set to 1. You can do several arithmetic operations at once. For instance, the following statement performs three operations:$result = 1 + 2 * 4 + 1; The order in which the arithmetic is performed is important. You can get different results depending on which operation is performed first. PHP does multiplication and division first, followed by addition and subtraction. If other considerations are equal, PHP goes from left to right. Consequently, the pre- ceding statement sets $result to 10, in the following order:$result = 1 + 2 * 4 + 1 (first it does the multiplication) $result = 1 + 8 + 1 (next it does the leftmost addition)$result = 9 + 1 (next it does the remaining addition) $result = 10 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 15. Chapter 6: General PHP 145 You can change the order in which the arithmetic is performed by using parentheses. The arithmetic inside the parentheses is performed first. For instance, you can write the previous statement with parentheses like this:$result = (1 + 2) * 4 + 1; This statement sets $result to 13, in the following order:$result = (1 + 2) * 4 + 1 (first it does the math in the parentheses) $result = 3 * 4 + 1 (next it does the multiplication)$result = 12 + 1 (next it does the addition) $result = 13 On the better-safe-than-sorry principle, it’s best to use parentheses whenever more than one answer is possible. Often, the numbers that you work with are dollar amounts, such as prod- uct prices. You want your customers to see prices in the proper format on Web pages. In other words, dollar amounts should always have two decimal places. However, PHP stores and displays numbers in the most efficient format. If the number is 10.00, it is displayed as 10. To put numbers into the proper format for dollars, you can use sprintf. The following statement for- mats a number into a dollar amount:$newvariablename = sprintf(“%01.2f”, $oldvariablename); This statement reformats the number in$oldvariablename and stores it in the new format in $newvariablename. For example, the following state- ments display money in the correct format:$price = 25; $f_price = sprintf(“%01.2f”,$price); echo “$f_price”; You see the following on the Web page: 25.00 sprintf can do more than format decimal places. For more information on using sprintf to format values, see Chapter 13. If you want commas to separate thousands in your number, you can use number_format. The following statement creates a dollar format with commas:$price = 25000; $f_price = number_format($price,2); echo “$f_price”; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 16. 146 Part III: PHP You see the following on the Web page: 25,000.00 The 2 in the number_format statement sets the format to two decimal places. You can use any number to get any number of decimal places. Working with Character Strings A character string is a series of characters. Characters are letters, numbers, and punctuation. When a number is used as a character, it’s just a stored character, the same as a letter. It can’t be used in arithmetic. For instance, a phone number is stored as a character string because it needs to be only stored — not added or multiplied. When you store a character string in a variable, you tell PHP where the string begins and ends by using double quotes or single quotes. For instance, the following two statements are the same:$string = “Hello World!”; $string = ‘Hello World!’; Suppose that you wanted to store a string as follows:$string = ‘It is Tom’s house’; echo $string; These statements won’t work because when PHP sees the ’ (single quote) after Tom, it thinks that this is the end of the string, and it displays the following: It is Tom You need to tell PHP to interpret the single quote (’) as an apostrophe instead of as the end of the string. You can do this by using a backslash (\) in front of the single quote. The backslash tells PHP that the single quote does not have any special meaning; it’s just an apostrophe. This is escaping the character. Use the following statements to display the entire string:$string = ‘It is Tom\’s house’; echo $string; Similarly, when you enclose a string in double quotes, you must also use a backslash in front of any double quotes in the string. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 17. Chapter 6: General PHP 147 Single-quoted strings versus double-quoted strings Single-quoted and double-quoted strings are handled differently. Single- quoted strings are stored literally, with the exception of \’, which is stored as an apostrophe. In double-quoted strings, variables and some special char- acters are evaluated before the string is stored. Here are the most important differences in the use of double or single quotes in code: ✓ Handling variables: If you enclose a variable in double quotes, PHP uses the value of the variable. However, if you enclose a variable in single quotes, PHP uses the literal variable name. For example, if you use the following statements:$age = 12; $result1 = “$age”; $result2 = ‘$age’; echo $result1; echo “”; echo$result2; the output is 12 $age ✓ Starting a new line: The special characters \n tell PHP to start a new line. When you use double quotes, PHP starts a new line at \n, but with single quotes, \n is a literal string. For instance, when using the follow- ing statements:$string1 = “String in \ndouble quotes”; $string2 = ‘String in \nsingle quotes’; string1 outputs as String in double quotes and string2 outputs as String in \nsingle quotes ✓ Inserting a tab: The special characters \t tell PHP to insert a tab. When you use double quotes, PHP inserts a tab at \t, but with single quotes, \t is a literal string. For instance, when using the following statements:$string1 = “String in \tdouble quotes”; $string2 = ‘String in \tsingle quotes’; string1 outputs as String in double quotes and string2 outputs as String in \tsingle quotes Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 18. 148 Part III: PHP The quotes that enclose the entire string determine the treatment of vari- ables and special characters, even if other sets of quotes are inside the string. For example, look at the following statements:$number = 10; $string1 = “There are ‘$number’ people in line.”; $string2 = ‘There are “$number” people waiting.’; echo $string1,”\n”; echo$string2; The output is as follows: There are ‘10’ people in line. There are “$number” people waiting. Joining strings You can join strings, a process called concatenation, by using a dot (.). For instance, you can join strings with the following statements:$string1 = ‘Hello’; $string2 = ‘World!’;$stringall = $string1.$string2; echo $stringall; The echo statement outputs HelloWorld! Notice that no space appears between Hello and World. That’s because no spaces are included in the two strings that are joined. You can add a space between the words by using the following concatenation statement rather than the earlier statement:$stringall = $string1.” “.$string2; You can use .= to add characters to an existing string. For example, you can use the following statements in place of the preceding statements: $stringall = “Hello”;$stringall .= “ World!”; echo $stringall; The echo statement outputs this: Hello World! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 19. Chapter 6: General PHP 149 You can also take strings apart. You can separate them at a given character or look for a substring in a string. You use functions to perform these and other operations on a string. I explain functions in Chapter 7. Working with Dates and Times Dates and times can be important elements in a Web database application. PHP has the ability to recognize dates and times and handle them differently than plain character strings. Dates and times are stored by the computer in a format called a timestamp. However, this is not a format in which you or I would want to see the date. PHP converts dates from your notation into a timestamp that the computer understands and from a timestamp into a format familiar to people. PHP handles dates and times by using built-in functions. The timestamp format is a Unix Timestamp, which is an integer that is the number of seconds from January 1, 1970, 00:00:00 GMT (Greenwich Mean Time) to the time represented by the timestamp. This format makes it easy to calculate the time between two dates — just subtract one timestamp from the other. Setting local time The current time is a tricky concept on the Web. The current time is the time stored in the server where PHP is running. If you’re using a Web hosting company, you probably don’t even know where your Web hosting company maintains the servers that house your Web site. In addition, the visitors that visit your Web site might be anywhere in the world. Consequently, you rarely want to display the current time on your Web site. Even the date can be dif- ferent if your Web server and the visitor are enough time zones apart. If you have a reason to want to display the current time in a specific location, you do that by including the following statement in your script: date_default_timezone_set(timezone); where timezone is a code for the time zone that you want to use. For exam- ple, you might use date_default_timezone_set(“America/Los_Angeles”) You can find a list of the time zone codes in Appendix H of the PHP online documentation at www.php.net/manual/en/timezones.america.php. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 20. 150 Part III: PHP On your local computer, if you’re using PHP 5.1 or later, you probably need to set a default time zone. If no default time zone is set, PHP guesses, which sometimes results in GMT. In addition, PHP displays a message advising you to set your local time zone. You can set your time zone in the php.ini file: 1. Open php.ini in a text editor. 2. Scroll down to the section headed [Date]. 3. Find the setting date.timezone =. 4. If the line begins with a semicolon (;), remove the semicolon. 5. Add a time zone code after the equal sign. You can see which time zone is currently your default time zone by using the following:$def = date_default_timezone_get() echo $def; Formatting a date The function that you will use most often is date, which converts a date or time from the timestamp format into a format that you specify. The general format is$mydate = date(“format”,$timestamp);$timestamp is a variable with a timestamp stored in it. You previously stored the timestamp in the variable, using a PHP function as I describe later in this section. If $timestamp is not included, the current time is obtained from the operating system and used. Thus, you can get today’s date with the following:$today = date(“Y/m/d”); If today is August 10, 2009, this statement returns 2009/08/10 The format is a string that specifies the date format that you want stored in the variable. For instance, the format “y-m-d” returns 09-08-10, and “M.d.Y” returns Aug.10.2009. Table 6-2 lists some of the symbols that you can use in the format string. (For a complete list of symbols, see the docu- mentation at www.php.net/manual/en/function.date.php.) You can separate the parts of the date with a hyphen (-), a dot (.), a forward slash (/), or a space. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.