1. Trang chủ
  2. » Công Nghệ Thông Tin

Sams Teach Yourself PHP, MySQL and Apache in 24 Hours phần 5 ppsx

73 216 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 73
Dung lượng 4,34 MB

Nội dung

When the loop reaches the file named "0", the string returned by readdir() resolves to false, which causes the loop to end. The approach in Listing 10.14 uses === to check that the return value returned by readdir() is not exactly equivalent to false. 0 only resolves to false in the test, so we circumvent the problem. If you find the ordering of items in a directory listing to be arbitrary, it's because the order is determined by the file system. If you want the items ordered in a specific fashion, you must read the contents into an array, which can then be sorted to your liking and subsequently displayed. [ Team LiB ] [ Team LiB ] Summary In this hour, you learned how to use include() to incorporate files into your documents and to execute any PHP code contained in include files. You learned how to use some of PHP's file test functions. You explored functions for reading files by the line, by the character, and in arbitrary chunks. You learned how to write to files, either replacing or appending to existing content. Finally, you learned how to create, remove, and read directories. Now that we can work with files, we can save and access substantial amounts of data. If we need to look up data from large files, however, our scripts begin to slow down quite considerably. What we need is some kind of database. [ Team LiB ] [ Team LiB ] Q&A Q1: Does the include() statement slow down my scripts? A1: Because an included file must be opened and parsed by the engine, it adds some overhead. However, the benefits of reusable code libraries often outweigh the relatively low performance overhead. Q2: Should I always end script execution if a file cannot be opened for writing or reading? A2: You should always allow for this possibility. If your script absolutely depends on the file you want to work with, you might want to use the die() function, writing an informative error message to the browser. In less critical situations, you still need to allow for the failure, perhaps by adding it to a log file. [ Team LiB ] [ Team LiB ] Workshop The workshop is designed to help you anticipate possible questions, review what you've learned, and begin putting your knowledge into practice. Quiz 1: What functions do you use to add library code to the currently running script? A1: You can use the require() or include() statement to incorporate PHP files into the current document. You could also use include_once() or require_once(). 2: What function do you use to find out whether a file is present on your file system? A2: You can test for the existence of a file with the file_exists() function. 3: How do you determine the size of a file? A3: The filesize() function returns a file's size in bytes. 4: What function do you use to open a file for reading or writing? A4: The fopen() function opens a file. It accepts the path to a file and a character representing the mode. It returns a file resource. 5: What function do you use to read a line of data from a file? A5: The fgets() function reads data up to the buffer size you pass it, the end of the line, or the end of the document, whichever comes first. 6: How can you tell when you've reached the end of a file? A6: The feof() function returns true when the file resource it's passed reaches the end of the file. 7: What function do you use to write a line of data to a file? A7: You can write data to a file with the fputs() function. 8: How do you open a directory for reading? A8: The opendir() function enables you to open a directory for reading. 9: What function do you use to read the name of a directory item after you've opened a directory for reading? A9: The readdir() function returns the name of a directory item from an opened directory. Activities Create a form that accepts a user's first and second name. Create a script that saves this data to a file. 1. Create a script that reads the data file you created in activity 1. In addition to writing its contents to the browser (adding a <BR> tag to each line), print a summary that includes the number of lines in the file and the file's size. 2. [ Team LiB ] [ Team LiB ] Hour 11. Working with Dates and Times Dates are so much a part of everyday life that it becomes easy to work with them without thinking. However, the quirks of the Gregorian calendar can be difficult to work with in programs. Fortunately, PHP provides powerful tools for date arithmetic that make date manipulation an easy task. Similarly, MySQL comes with its own set of date-related functions. You learn about these in this hour as well, and find that MySQL can take a lot of the programming burden off your hands. In this hour, you will learn How to acquire the current date and time How to get information about a date How to format date information How to test dates for validity How to set dates How to use MySQL's date and time-related functions How to format date and time results in MySQL How to find and express intervals between dates and times using MySQL [ Team LiB ] [ Team LiB ] Using Date and Time Functions in PHP The several sections that follow introduce you to the date- and time-related functions specifically in PHP. You learn about the MySQL functions later in this hour. Try each listing yourself, as you march along through this hour. Getting the Date with time() PHP's time() function gives you all the information that you need about the current date and time. It requires no arguments and returns an integer. For us humans, the returned number is a little hard on the eyes, but it's extremely useful nonetheless. print time(); // sample output: 1127732399 The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the Unix epoch , and the number of seconds that have elapsed since then is referred to as a timestamp . PHP offers excellent tools to convert a timestamp into a form that humans are comfortable with. Even so, isn't a timestamp a needlessly convoluted way of storing a date? In fact, the opposite is true. From just one number, you can extract enormous amounts of information. Even better, a timestamp can make date arithmetic much easier than you might imagine. Think of a homegrown date system in which you record days of the month as well as months and years. Now imagine a script that must add one day to a given date. If this date happened to be 31 December 1999, rather than adding 1 to the date, you'd have to write code to set the day of the month to 1, the month to January, and the year to 2000. Using a timestamp, you need only add a day's worth of seconds to your current figure and you're done. You can convert this new figure into something more friendly at your leisure. Converting a Timestamp with getdate() Now that you have a timestamp to work with, you must convert it before you present it to the user. getdate() optionally accepts a timestamp and returns an associative array containing information about the date. If you omit the timestamp, getdate() works with the current timestamp as returned by time() . Table 11.1 lists the elements contained in the array returned by getdate() . seconds Seconds past the minute (0–59) 28 minutes Minutes past the hour (0–59) 7 hours Hours of the day (0–23) 12 mday Day of the month (1–31) 20 wday Day of the week (0–6) 4 mon Month of the year (1–12) 1 year Year (4 digits) 2000 yday Day of year (0–365) 19 weekday Day of the week (name) Thursday month Month of the year (name) January 0 Timestamp 948370048 Table 11.1. The Associative Array Returned by getdate() Key Description Example Listing 11.1 uses getdate() (line 7) to extract information from a timestamp, employing a foreach statement to print each element (line 8). You can see typical output in Figure 11.1 . getdate() returns the date according to the local time zone. Figure 11.1. Using getdate() . Listing 11.1 Acquiring Date Information with getdate() 1: <html> 2: <head> 3: <title>Listing 11.1 Acquiring date information with getdate()</title> 4: </head> 5: <body> 6: <?php 7: $date_array = getdate(); // no argument passed so today's date will be used 8: foreach ($date_array as $key => $val) { 9: print "$key = $val<br>"; 10: } 11: ?> 12: <hr> 13: <? 14: print "Today's date: ".$date_array['mday']."/".$date_array['mon']."/". 15: $date_array['year']."<p>"; 16: ?> 17: </body> 18: </html> Converting a Timestamp with date() You can use getdate() when you want to work with the elements that it outputs. Sometimes, though, you want to display the date as a string. The date() function returns a formatted string that represents a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it. In addition to the format string, date() optionally accepts a timestamp. Table 11.2 lists the codes that a format string can contain. Any other data you include in the format string passed to date() is included in the return value. a am or pm (lowercase) pm A AM or PM (uppercase) PM d Day of month (number with leading zeroes) [...]... Number of minutes MINUTE Number of hours HOUR Number of days DAY Number of months MONTH Number of years YEAR "minutes:seconds" MINUTE_SECOND "hours: minutes" HOUR_MINUTE "days hours" DAY_HOUR "years-months" YEAR_MONTH "hours: minutes:seconds" HOUR_SECOND "days hours: minutes" DAY_MINUTE "days hours: minutes:seconds" DAY_SECOND Table 11.4 Values and Types in Date Arithmetic Value Type For example, to find the... + | 53 | + + 1 row in set (0.00 sec) Working with Hours, Minutes, and Seconds If you're using a date that includes the exact time, such as datetime or timestamp , or even just a time field, there are functions to find the hours, minutes, and seconds from that string Not surprisingly, these functions are called HOUR() , MINUTE() , and SECOND() HOUR() returns the hour in a given time,... using mktime(), and how to test a date for validity with checkdate() Additionally, you discovered that MySQL' s built -in date and time functions can definitely take some of the load off your application by internally formatting dates and times and performing the date and time arithmetic The formatting options used for the DATE_FORMAT() function provide a simple method to produce a custom display string... help you anticipate possible questions, review what you've learned, and begin putting your knowledge into practice Quiz 1: A1: Using PHP, how do you acquire a Unix timestamp that represents the current date and time? What about using MySQL? In PHP, use time() In MySQL, use UNIX_TIMESTAMP() 2: Which PHP function accepts a timestamp and returns an associative array that represents the given date? A2:... day after that specified in the month, day, and year arguments Save the text of this listing in a file called You should see: listing11.2.php and open it in your Web browser 08/23/02 4. 15: 00 The date is 23 of August 2002, at 4. 15 am Testing a Date with checkdate() You might need to accept date information from user input Before you work with a user-entered date or store it in a database, you should... mktime() using these values, you'd end up with a timestamp of -1 As a rule of thumb, don't use mktime() with years before 1902, and be cautious of using date functions with any date before 1970 You learn more about using checkdate() in Hour 12 , "Creating a Simple Calendar." [ Team LiB ] [ Team LiB ] Using Date and Time Functions in MySQL MySQL's built -in date-related functions can be used in SELECT... this listing in a file called listing11.2.php and open it in your Web browser Your date will differ from the following, obviously, but here's some sample output: 09/16/02 8 .52 :06 Today is 16 of September 2002, at 8 .52 am Although the format string looks arcane, it's easy to build If you want to add a string that contains letters that are also format codes to the format, you can escape them by placing a... with the date() function Listing 11.3 Creating a Timestamp with mktime() 1: 2: 3: 4: Listing 11.3 Creating a timestamp with mktime() 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: . functions How to format date and time results in MySQL How to find and express intervals between dates and times using MySQL [ Team LiB ] [ Team LiB ] Using Date and Time Functions in PHP The several. (adding a <BR> tag to each line), print a summary that includes the number of lines in the file and the file's size. 2. [ Team LiB ] [ Team LiB ] Hour 11. Working with Dates and. Table 11.1 lists the elements contained in the array returned by getdate() . seconds Seconds past the minute (0 59 ) 28 minutes Minutes past the hour (0 59 ) 7 hours Hours of the day (0–23) 12 mday Day

Ngày đăng: 13/08/2014, 21:21