Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
1,52 MB
Nội dung
31CHAPTER 2 • INTRODUCING PHP Taking Advantage of Functions Earlier in this chapter you learned what a function is: a bit of code packaged in such a way that it can be repeatedly executed by referring to its dened name. For example, in this chapter you've already encountered the printf() function. As you might imagine, PHP offers many more functions capable of performing a seemingly countless number of tasks, ranging from rounding fractions down to count- ing the number of characters in a string, to redirecting a visitor to another website. To obtain a better idea of just how many functions are at your disposal, take some time to peruse PHP's manual. In this section you'll become better acquainted with functions by formally introducing a function you'll repeatedly return to when building PHP-powered websites. Introducing the date() Function The date() function is very powerful, allowing you to format not only the current date, but also the current time in a wide variety of ways. For example, presuming today's date was July 4, 2009, among many other formats you could easily output the current date and time using any of the following formats: July 4, 2009 07/04/2009 07/04/09 Saturday Sat, 04 July 2008 The date() function can also output the current time in a wide variety of formats such as: 08:15 pm 20:15 11:40 am EST 11:40 am -0500 Although not mandatory, many functions accept one or more input parameters which help determine how the function behaves. Indeed, the date() function accepts two, a required parameter which tells it how to return the date and/or time, and an optional parameter which tells it to format a specic date and time in accordance with a supplied timestamp (more about what a timestamp is in a moment). Additionally, a function will always return a value, even if that value is nothing (or void, as they say in computer science-ese). In the date() function's case, it returns a string, consisting of the desired formatted date and time. NOTE. Typically you'll learn about a function by consulting the PHP manual. Incidentally, if you already know the function's name you can navigate directly to it by using the following URL: http://www.php.net/function, where function is a placeholder for the name of the function you'd like to consult. Therefore to consult the date() function's page, navigate to http://www. php.net/date. When consulting the PHP manual to learn more about a specic function, keep in mind that each function's page clearly identies the return value, and which input parameters are optional by enclos- Download at Boykma.Com 32 CHAPTER 2 • INTRODUCING PHP ing them within square brackets. For instance if you navigate over to http://www.php.net/date you'll see the date() function dened like this: string date( string $format [, int $timestamp] ) So what do you assign the $format input parameter in order to specify what sort of date/time it should return? This is done by assigning format speciers to the parameter in a certain order. For- mat speciers are simply a variety of different characters, with each having a specic meaning. For example, to have date() return just the current day of the week, you would assign the lowercase l to $format, like so: echo date('l'); Presuming today is Tuesday, it will return: Tuesday If you're just looking for the current month, you use the F character: echo date('F'); Let's consider a more involved example. Suppose you want to return the current date using this for- mat: March 11, 2008: echo date('F j, Y'); Finally, let's return the current date and time using this format: 11-13-09 2:47 pm: echo date('m-d-y g:i a'); So how do you keep all of these parameters straight in your head? The simple answer is, you don't. The PHP manual is always just a few keystrokes away, and you can even download a copy to your computer by navigating to http://www.php.net/docs.php. Hopefully this brief section has provided you with some insight into not only how to use functions, but also into one of PHP's most popular features, date(). Try building upon what you've learned here by experimenting with some of my other favorite functions, including strtoupper(), str_ word_count(), and pi(). Remember you can easily look these up by appending the function name to http://www.php.net/! Dening Your Own Functions While the PHP language is bundled with an amazing array of diverse functions, sooner or later you'll want a function capable of carrying out a task very specic to your own needs. For example, suppose some future version of your gaming web site started selling copies of used video games, and because your business is run out of Ohio you need to calculate sales tax for Ohio-based purchasers. This sort of task might be used at several locations throughout your website, so creating a function capable of calculating the sales tax seems like a good idea. The following listing demonstrates how such a func- Download at Boykma.Com 33CHAPTER 2 • INTRODUCING PHP tion is created and subsequently called: 01 <?php 02 03 function calculateSalesTax($price, $tax) { 04 return ($price * $tax) + $price; 05 } 06 07 echo "Total cost: {calculateSalesTax(9.99, .0575)}"; 08 09 ?> Let's review this script: • Line 03 begins the function denition, assigning a name and identifying any input param- eters. • Within the function body (line 04) you'll see the total cost is calculated, with the return key- word used to return that value to the caller. Of course, you're not constrained to immediately output the returned value. For instance, if you wanted to assign the return value to another variable, perhaps in order to perform additional process- ing, you could call calculateSalesTax() like this: $total = calculateSalesTax(9.99, .0575); Conditional Statements Most computer programs are like owcharts, with their execution dependent upon a select set of conditions. In order to determine which route the program will take, conditional statements are often used. These statements are used to validate a given condition, such as what rating applies to which denition. For example, suppose you wanted to offer a user-friendly message based on the video game's rating: if ($rating == 'T') { echo 'Rated T for Teens!'; } Notice I used two equal signs here. This is because we're comparing $rating to 'T' rather than assign- ing $rating the value of 'T'. Of course, you might want to offer an alternative message to the visitor in case the rating isn't avail- able. This is easily accomplished with the if-else statement: if ($rating == 'T') { echo 'Rated T for Teens!'; } else { echo 'No rating available!'; } Download at Boykma.Com 34 CHAPTER 2 • INTRODUCING PHP As a nal example, what if you wanted to check a value against more than two conditions? For instance, you could use PHP's if-elseif-else conditional statement to create a custom suggestion based on a game's rating and whether it has support for multiple players: if ($rating == 'T' AND $multiplayer == 'Y'){ echo 'Suitable for playing with your friends after school!'; } elseif ($rating == 'M' AND $multiplayer == 'Y') { echo 'Bring your coworkers together with a night of gaming!'; } else { echo 'Sorry, no suggestion available for this game!'; } Looping Statements Even the simplest of web applications will likely require you to iterate over a set of data. For ex- ample, in the earlier introduction to arrays you learned how to selectively output array elements, but what if you wanted to output all of them? Explicitly identifying each array index in an echo() statement wouldn't make much sense, so instead you'll logically want an easier solutions for doing so. PHP's looping statements offer that solution. In this section I'll introduce you to the three most popular looping statements, although you're encour- aged to consult the PHP manual to review other less commonly used alternatives. The while Loop The while loop iterates until a certain condition is met. For example, the script shown next (while1. php in your code download) will output 'I love video games!' ten times. 01 <?php 02 03 // Set a looping counter 04 $count = 1; 05 06 // Output 'I love video games!' until the counter reaches 10 07 while ($count <= 10) { 08 09 echo 'I love video games! <br />'; 10 11 // Increment the counter 12 $count++; 13 14 } 15 ?> Let's review this script: • Line 04 sets a starting point for subsequently comparing $count to 10. Because the while loop condition (line 07) species it will execute until $count equals 10, the loop will execute a total of ten times. Download at Boykma.Com 35CHAPTER 2 • INTRODUCING PHP • Line 12 increments the counter using the increment operator (++). This is just a shortcut for incrementing an integer by 1. For instance, you could alternatively use the longhand version of this line: $count = $count + 1. Similarly, a decrement operator ( ) exists for decre- menting an integer value by 1. As you might have guessed, executing this script produces output identical to that shown in Figure 2-3. Figure 2-3. Using a while loop Let's consider a more practical example. Recalling the $games single-dimensional array created in the introductory section on arrays, suppose you wanted to output each game name to the browser. The counter would logically be equivalent to the size of the array, which you can determine using the count() function. The next example demonstrates how to use count() alongside an introduction to using the while loop to output the $games array: 01 <?php 02 03 // Create the array 04 $games = array('Arkanoid Live!', 'Tekken 6', 'Duke Nukem 3D'); 05 06 // Start the counter at 0 in order to retrieve the rst element 07 $count = 0; 08 09 // Loop through the array until the end is reached 10 while ($count < count($games)) { 11 echo "{$games[$count]}<br />"; Download at Boykma.Com 36 CHAPTER 2 • INTRODUCING PHP 12 $count++; 13 } 14 ?> Let's review this script (while2.php in your code download): • Line 10's conditional statement might leave you scratching your head. Why are we only loop- ing while $count is less than the size of $games, rather than until it's equal to the array size? Remember that PHP considers array offsets to begin at 0, meaning when $count is equal to count($games) - 1, we've reached the end of the array. Executing this script produces the output shown in Figure 2-4. Figure 2-4. Displaying array elements using the while loop The for Loop The for loop accomplishes the same task as while, looping over a group of statements until a certain condition is met. The only difference is the counter is managed alongside the conditional statement rather than within the looping body. Whether you choose while or for is simply a matter of prefer- ence. As an example, the following script ( for.php) outputs the $games array in the same fashion as was demonstrated in the previous example: Download at Boykma.Com 37CHAPTER 2 • INTRODUCING PHP 01 <?php 03 04 // Create the array 05 $games = array('Arkanoid Live!', 'Tekken 6', 'Duke Nukem 3D'); 07 08 // Loop through the array until the end is reached 09 for ($count = 0; $count < count($games); $count++) { 10 echo "{$games[$count]} <br />"; 11 } 12 13 ?> Let's review the script: • The for loop ultimately produces identical results to a similarly constrained while loop, only that the initial value, condition, and iterator are packaged into the loop arguments. So in this case $count is rst set to 0 (this rst argument executes only once). Subsequently with each iteration the second argument is executed, followed by the execution of the third. If the sec- ond evaluates to true, the loop body will execute. The output of this script is identical to that shown in Figure 2-4. The foreach Loop You learned how the for loop consolidates a bit of code otherwise required when using a while loop by packaging the iterator and conditional into a single line. However when iterating over an array there exists yet another looping mechanism which can further cut down on this code. The foreach looping statement will iterate over an array, automatically retrieving the next element each time it loops. For example, the following foreach loop reproduces the same output as that shown in Figure 2-4 when passed the same array: 01 <?php 02 03 foreach ($games as $game) { 04 echo "{$game}<br />"; 05 } 06 07 ?> The foreach loop also offers a secondary syntax useful for peeling keys and their corresponding val- ues from associative arrays. For instance you might recall the $states associative array from earlier in this chapter: $states = array('CA' => 'California', 'OH' => 'Ohio', 'NY' => 'New York'); The foreach statement can iterate through this array, retrieving each key and its value, using the fol- lowing syntax: Download at Boykma.Com 38 CHAPTER 2 • INTRODUCING PHP 01 <?php 02 foreach($states AS $key => $value) { 03 echo "{$value} ({$key})<br />"; 04 } 05 ?> Executing this example produces the output shown in Figure 2-5. Figure 2-5. Using the foreach Loop Step #2. Publishing Spreadsheet Data to the Web Suppose your idea for building a website showcasing your video game collection sprung from the frustrations encountered when attempting to keep friends informed about your games and which are currently being borrowed. So far you've been managing the game collection in a simple spreadsheet, with each row containing information about a specic game. For each game you've cataloged the title, platform, price, whether a friend is borrowing it, and a few words regarding your general opinion about the game. A sample of what the spreadsheet looks like is found in Figure 2-6. Download at Boykma.Com 39CHAPTER 2 • INTRODUCING PHP Figure 2-6. The game spreadsheet As you've distributed the spreadsheet to friends over a period of months, various copies have become outdated and it's causing quite a bit of confusion. Mitch wants to borrow NBA 2K7 but his version of the spreadsheet indicates Sean has it, although Sean actually returned it weeks ago. Scott wants to buy Gears of War from you but you already sold it. And nobody seems to know you've been playing Madden 2009 day and night for weeks now. Multiple versions of the spreadsheet are causing a giant headache, and so you've decided to create a website which all of your friends can simply refer to for updates. All you need to do is gure out how to make the spreadsheet available online. Converting the Spreadsheet To make your spreadsheet data available online, you'll need to rst convert it to CSV, or Comma-Sep- arated Values format. CSV isn't formally a standard format, although it's supported by many applica- tions and languages as a generally agreed upon way to share data, PHP included. As Microsoft Excel remains far-and-away the most popular spreadsheet creation and analysis application, I'll show you how to convert an Excel spreadsheet to CSV format. Saving an Excel spreadsheet in CSV format is very simple; just open up the spreadsheet in Excel and then navigate to File -> Save As. The Save As dialog will appear as shown in Figure 2-7. Navigate to a desired save destination, assign the le an easily-recognizable name, and from the Save As Type drop-down menu choose CSV (comma delimited). Finally, press the Save button to create the CSV le. Figure 2-7. Saving the spreadsheet as a CSV le If you open up this le in a text editor, you'll see that each spreadsheet eld is separated by a comma. To prevent any confusion which might arise due to commas found in any of the elds, Excel delimit- Download at Boykma.Com 40 CHAPTER 2 • INTRODUCING PHP ed those elds with quotation marks. For example, a few lines found in the games.csv le are shown here: Title,Platform,Price,Borrowed?,Comments Halo 3,Xbox 360,$59.99,No,Love the online multiplayer Spy Hunter,Nintendo Gameboy,$12.99,No, FIFA 2006,Nintendo Gameboy,$12.00,No, Saint's Row,Xbox 360,$59.99,No,Need to nish it Nascar 2008,Xbox 360,$49.99,Scott (10/1/2008),Hard to drive cars Call of Duty 4,Xbox 360,$59.99,No,My favorite game! NBA 2K7,Xbox 360,$59.99,Sean (9/15/2008), Super Mario Bros 3,Nintendo Gameboy,$19.99,No, Gears of war,Xbox 360,$59.99,No,Would like to sell or trade Later in this section I'll show you how to disregard these quotation marks when parsing the CSV le. TIP. Chances are you're going to eventually include a comma in the text found in one of the col- umns, which will present a problem when you later write a script to parse the CSV le. The most effective solution is to change the comma delimiter Excel uses to something you'll never use in the spreadsheet, for instance a vertical bar |. While Excel doesn't offer any way to change this, you can still change the delimiter by navigating to Start -> Control Panel -> Regional and Language Options. From here the process varies depending upon your version of Windows. If you're using Windows XP, click the Regional Options tab, then Customize, and change the separator found in the List separator box. If you're using Windows Vista, click the Regional Options tab, and then click Customize this format, and change the separator found in the List separator box. For the purposes of this exercise I'll forego using commas in any of the elds so we can just use the default setting. Reading the CSV File Next we'll write a short PHP script capable of reading the CSV le's contents, and formatting and displaying the data to the browser. To begin, place the newly saved CSV le within your application's home directory so the script can easily access it. NOTE. If you don't want visitors to be able to download your CSV le, you can instead place the le within PHP's include path, specied within PHP's php.ini conguration le by the include_ path directive. Next we'll create the script which will be used to parse the CSV le. Believe it or not, much of the task has already been implemented within a standard PHP function known as le(). The le() function will parse a le, dumping its contents into an array. In doing so, it treats each line as a new array element, with each line ending when it encounters the hidden newline (\n) character. For the rst iteration of our script (game_parse.php), we'll dump games.csv into an array, and then iterate over each line of the array, displaying each element to the browser: Download at Boykma.Com [...]... ".;c:\apache\htdocs\easyphpwebsites\code\chapter02" On Linux, this path might look like this: includes_path = "./usr/local/apache/htdocs/easyphpwebsites\code\chapter02" From here, the require() statement will looks for a templates directory as specified in the provided path in the script, and from there retrieve the header .php and footer .php files If you don't have the php. ini file at your disposal, then you're... INTRODUCING PHP 47 • Line 16 uses the PHP function explode() to parse just the first line of the array This results in retrieving the spreadsheet header names which we'll use for the table column headers • Lines 17-19 iterate through the $header array, placing each header title into the table header using the setHeaderContents() method Note the first parameter of this method is set to 0 because the table... specified the form destination to be listing3-1 php, the PHP code used to process the data hasn't yet been created In this section you'll create this script, and learn how to parse the data submitted by the user via the contact form Any PHP script defined as the form's submission destination can access the form data using an associative array called $_POST The array values can be accessed by referencing the. .. (game_final .php) To integrate the header and footer into your script, you'll use the require() statement This statement will retrieve the contents of the specified file, and integrate it into the calling page If any PHP logic is found in the file, that logic will be evaluated The following script (game_final .php) demonstrates how Figure 2-11 was created < ?php // Insert page header require('templates/header .php' )... $altRow); // Output the HTML table to the browser echo $table->toHtml(); Let's review some of this script's key lines: • Line 04 makes the HTML_Table package available to the script by "including it" into the document We'll talk more about the details of the require() command in the next section, including how the require() command was able to locate the package without having to define the complete path... charging the credit card a second time) If GET was mistakenly used for this purpose, the browser would logically not warn the user, allowing the page to be reloaded and the credit card potentially charged again (I say potentially because the developer should logically have built safeguards into the application to account for such accidents) Given the important distinction between these two methods, keep the. .. HTML_Table to format the game collection in a much more visually appealing fashion than what was achieved with the earlier approach The script we'll cover in this chapter will produce the table shown in Figure 2-10 Figure 2-10 Formatting the game collection using a table The next script (games_table .php) presents the code Following the listing is a breakdown of the script 01 < ?php 02 03 // Make HTML_Table... offset for the very first line is zero • Line 22 sets the CSS class for the header • Line 25 initiates the iteration of the remaining lines in the $games array In this for loop we'll repeatedly peel off the next row in the array (line 25), parse it into an array called $game (line 28), set the CSS class for each row (line 31), and then output each element into a tag • Lines 41-42 set another CSS... you'll find the game directory footer (footer .php) : Download at Boykma.Com 48 CHAPTER 2 • INTRODUCING PHP If you want to borrow a game, contact me! By inserting the header .php and footer .php scripts into their appropriate locations with the script displaying the table, we'll be able to achieve a result similar to that shown in Figure 2-11 Figure 2-11 The game... all of the elements using print_r() (The print_r() function was first introduced in Chapter 2) In fact, in Listing 3-2 we'll create the skeleton for what will ultimately become the index .php script by using print_r() to simply dump the sub- mitted form data to the browser Listing 3-2 Outputting submitted form data to the browser 01 < ?php 02 03 if ($_POST) 04 print_r($_POST); 05 06 ?> Obviously there . table In the case of the games spreadsheet, we want the table to expand and shrink based on the number of rows in the spreadsheet, therefore the table must be built dynamically. In the next. "./usr/local/apache/htdocs/easyphpwebsitescodechapter02" From here, the require() statement will looks for a templates directory as specied in the provided path in the script, and from there retrieve the. once). Subsequently with each iteration the second argument is executed, followed by the execution of the third. If the sec- ond evaluates to true, the loop body will execute. The output of this