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

How to do everything with PHP (phần 8) docx

50 361 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

334 How to Do Everything with PHP & MySQL HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter 16 HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter 16 Created with the sole goal of colonizing every single planet in the known Universe (and beyond), Megalomaniacs Inc. hopes to quickly acquire a monopoly over the vast tracts of uncharted real estate in space. Speaking at a press conference, Megalomaniacs Inc. CEO warned reporters that Megalomaniacs Inc. would "take everything it could, and then some". ', 'Peter Paul (peter@megalo.mania)', '2003- 12-11 17:29:25'); Query OK, 1 row affected (0.01 sec) mysql> INSERT INTO news (id, title, content, contact, timestamp) VALUES ( '2', 'Megalomaniacs Inc. Expands To Mars', 'MARS As part of its business strategy of "expand and swallow", Megalomaniacs Inc. today announced that it had successfully sent a team of corporate raiders to Mars, in an effort to persuade the inhabitants of that planet to surrender their planet for colonization. Megalomaniacs Inc. COO today said that the move was a "friendly overture", but that a failure to comply with the company\'s colonization plans would result in a "swift and sure eviction of those little green guys". ', 'Tim Jr. (tim@megalo.mania)', '2004-08-30 12:13:48'); Query OK, 1 row affected (0.07 sec) If the previous commands are unfamiliar to you, page back to Chapters 9 and 10, which explain them in greater detail. Listing and Displaying News Items You’ll remember from the requirements discussion a couple of pages back, that this development effort can broadly be split into two parts. One part consists of the scripts that retrieve the list of newest items from the database and display this list to the user. The other part consists of administrative tools that enable editors to manage this list, enter new information, and edit or delete existing information. Because the first part is simpler, let’s get that out of the way first. Two scripts are involved here: list.php, which retrieves a list of the five newest entries in the database; and story.php, which displays the full text for the selected story. ch16.indd 334 2/2/05 3:30:47 PM TEAM LinG HowTo8 (8) CHAPTER 16: Sample Application: News Publishing System 335 HowTo8 (8) Listing News Items Create list.php first: <html> <head> <basefont face="Verdana"> </head> <body> <! standard page header begins > <p>&nbsp;<p> <table width="100%" cellspacing="0" cellpadding="5"> <tr> <td></td> </tr> <tr> <td bgcolor="Navy"><font size="-1" color="White"> <b>Megalomaniacs Inc : Press Releases</b></font> </td> </tr> </table> <! standard page header ends > <ul> <?php // includes include(' /conf.php'); include(' /functions.php'); // open database connection $connection = mysql_connect($host, $user, $pass) ↵ or die ('Unable to connect!'); // select database mysql_select_db($db) or die ('Unable to select database!'); // generate and execute query $query = "SELECT id, title, timestamp FROM news ↵ ORDER BY timestamp DESC LIMIT 0, 5"; $result = mysql_query($query) ↵ or die ("Error in query: $query. " . mysql_error()); 16 ch16.indd 335 2/2/05 3:30:48 PM TEAM LinG 336 How to Do Everything with PHP & MySQL HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter 16 HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter 16 // if records present if (mysql_num_rows($result) > 0) { // iterate through resultset // print article titles while($row = mysql_fetch_object($result)) { ?> <li><font size="-1"><b><a href="story.php?id= ↵ <?php echo $row->id; ?>"><?php echo $row->title; ?></a></b></font> <br> <font size="-2"><?php echo formatDate($row->timestamp); ?> </font> <p> <?php } } // if no records present // display message else { ?> <font size="-1">No press releases currently available</font> <?php } // close database connection mysql_close($connection); ?> </ul> <! standard page footer begins > <p> <table width="100%" cellspacing="0" cellpadding="5"> <tr> <td align="center"><font size="-2"> All rights reserved. Visit Melonfire <a href="http://www.melonfire.com/community/columns/trog/"> here</a> for more.</td> </tr> </table> <! standard page footer ends > </body> </html> ch16.indd 336 2/2/05 3:30:48 PM TEAM LinG HowTo8 (8) CHAPTER 16: Sample Application: News Publishing System 337 HowTo8 (8) This script connects to the database, retrieves a set of records, and formats them for display in a web browser. You’ve already seen this in Chapter 13, so none of it should be a surprise. Pay special attention to the SELECT query that retrieves the records from the MySQL table: it contains a DESC clause to order the items in the order of most recent first, and a LIMIT clause to restrict the result set to five items only. The formatDate() function used in the previous code listing is a user- defined function that turns a MySQL timestamp into a human-friendly date string (Chapter 5 has more information on how to define such a function). The function is defined in the functions.php file and looks like this: <?php // format MySQL DATETIME value into a more readable string function formatDate($val) { $arr = explode('-', $val); return date('d M Y', mktime(0,0,0, $arr[1], $arr[2], $arr[0])); } ?> Also necessary is to include some code that tells the script what to do if no records are returned by the query (this could happen when the application is installed for the first time, and no records are present in the database). Without this code, the generated page would be completely empty—not a nice thing to show to users, especially on a potentially high-traffic page. The solution is to use an if() loop to check if any records were returned by the query and display a neat little message if none were returned. Here’s a fragment that outlines how this would work: <?php // if records present if (mysql_num_rows($result) > 0) { // iterate through resultset // print article titles } // if no records present else 16 ch16.indd 337 2/2/05 3:30:48 PM TEAM LinG 338 How to Do Everything with PHP & MySQL HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter 16 HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter 16 { // display error message } ?> Figure 16-1 shows what it looks like when you view this script through a browser. As a developer, it’s important to think through all possible situations and write code that handles each one intelligently. The possibility of an empty database doesn’t even occur to many novice developers—and this can lead to embarrassing situations if you’re demonstrating the application to your boss . . . or worse, the customer! FIGURE 16-1 A list of available news items ch16.indd 338 2/2/05 3:30:49 PM TEAM LinG HowTo8 (8) CHAPTER 16: Sample Application: News Publishing System 339 HowTo8 (8) The Configuration File In case you’re wondering, the MySQL hostname, the username, and the password used by the mysql_connect() function are all variables sourced from the configuration file conf.php. This file has been include()-d at the top of each script and it looks like this: <?php // database configuration $host = 'localhost'; $user = 'newuser'; $pass = 'newspass'; $db = 'news'; // default contact person $def_contact = 'Johnny Doe (jd@megalo.mania)'; ?> Extracting this configuration information into a separate file makes it easier to update the application in case the database username or password changes. Updating a single file is far easier than updating multiple scripts, each with the values hard-wired into it. Displaying Story Content You’ll notice, from the previous code listing, that every press release title is linked to story.php via its unique ID. The story.php script uses this ID to connect to the database and retrieve the full text of the release. Here is what it looks like: <html> <head></head> <body> <! standard page header > <?php // includes include(' /conf.php'); include(' /functions.php'); 16 ch16.indd 339 2/2/05 3:30:49 PM TEAM LinG 340 How to Do Everything with PHP & MySQL HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter 16 HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter 16 // check for record ID if ((!isset($_GET['id']) || trim($_GET['id']) == '')) { die('Missing record ID!'); } // open database connection $connection = mysql_connect($host, $user, $pass) ↵ or die ('Unable to connect!'); // select database mysql_select_db($db) or die ('Unable to select database!'); // generate and execute query $id = $_GET['id']; $query = "SELECT title, content, contact, timestamp FROM news ↵ WHERE id = '$id'"; $result = mysql_query($query) ↵ or die ("Error in query: $query. " . mysql_error()); // get resultset as object $row = mysql_fetch_object($result); // print details if ($row) { ?> <p> <b><?php echo $row->title; ?></b> <p> <font size="-1"><?php echo nl2br($row->content); ?></font> <p> <font size="-2">This release was published on <?php echo formatDate($row->timestamp); ?>. For more information, please contact <?php echo $row->contact; ?> </font> <?php } else { ?> <p> <font size="-1">That release could not be located in our database.</font> <?php } ch16.indd 340 2/2/05 3:30:49 PM TEAM LinG HowTo8 (8) CHAPTER 16: Sample Application: News Publishing System 341 HowTo8 (8) // close database connection mysql_close($connection); ?> <! standard page footer > </body> </html> Again, extremely simple—connect, use the ID to get the full text for the corresponding item, and display it. Figure 16-2 illustrates what it looks like. At this point, you have a primitive publishing system that can be used to provide users of a web site with news, press releases, and other information. There’s only one small hitch. . . . FIGURE 16-2 Displaying story content 16 ch16.indd 341 2/2/05 3:30:49 PM TEAM LinG 342 How to Do Everything with PHP & MySQL HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter 16 HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter 16 Manipulating News Items At this point in time, there is no simple way to update the database with new information. To insert or edit information, an administrator needs to know SQL and have access to a MySQL client. This may not always be possible, so it’s necessary to also develop a simple, friendly interface for database updates. Based on the requirements outlined previously, this administration module will consist of at least the following four scripts: list.php, which lists all press releases currently in the database and lets the administrator select an individual record for an edit or delete operation; edit.php, which enables the administrator to update a record; delete.php, which lets the administrator delete a record; and add.php, which enables the administrator to add a new record. Let’s look at each of these in turn. Listing News Items First up, the list.php script. As you might imagine, this is almost identical to the previous list.php—it displays a list of all press releases currently stored in the database, with additional links to edit or delete them. Here it is. <html> <head></head> <body> <! standard page header > <?php // includes include(' /conf.php'); include(' /functions.php'); // open database connection $connection = mysql_connect($host, $user, $pass) ↵ or die ('Unable to connect!'); // select database mysql_select_db($db) or die ('Unable to select database!'); // generate and execute query $query = "SELECT id, title, timestamp FROM news ORDER BY timestamp ↵ DESC"; ch16.indd 342 2/2/05 3:30:49 PM TEAM LinG HowTo8 (8) CHAPTER 16: Sample Application: News Publishing System 343 HowTo8 (8) $result = mysql_query($query) ↵ or die ("Error in query: $query. " . mysql_error()); // if records present if (mysql_num_rows($result) > 0) { // iterate through resultset // print title with links to edit and delete scripts while($row = mysql_fetch_object($result)) { ?> <font size="-1"><b><?php echo $row->title; ?></b> [<?php echo formatDate($row->timestamp); ?>]</font> <br> <font size="-2"><a href="edit.php?id=<?php echo $row->id; ?>"> edit</a> | <a href="delete.php?id=<?php echo $row->id; ?>"> delete</a></font> <p> <?php } } // if no records present // display message else { ?> <font size="-1">No releases currently available</font><p> <?php } // close connection mysql_close($connection); ?> <font size="-2"><a href="add.php">add new</a></font> <! standard page footer > </body> </html> Pay special attention to the links to edit.php and delete.php in the previous script. You’ll see that each of these scripts is passed an additional $id variable, which contains the unique record identifier for that particular item. More on this shortly. 16 ch16.indd 343 2/2/05 3:30:50 PM TEAM LinG [...]... or equal to) operator, effect of, 71 syntax, displaying variable values with, 88 (not equal to/ not of same type) operator, effect of, 71 = (assignment operator), using with variable values, 65 != (not equal to) operator, effect of, 71 == (equal to) operator, effect of, 71 !== (not equal to/ not of same type) operator, effect of, 71 === (equal to/ of same type) comparison operator, example... address for, 258 dollar ($) symbol, using before variables, 64 dolphin logo, significance of, 14 domain attribute, using with cookies, 126 DOUBLE numeric type, description of, 164–165 double quotes ("), using with string values, 69 do- while() loop, example of, 89–90 DROP DATABASE command, using, 177–178 DROP PRIMARY KEY clause, using with tables, 174 TEAM LinG 368 How to Do Everything with PHP & MySQL DROP... able to download it! That said, note that the default Apache configuration blocks remote retrieval of any file beginning with ht Next, open your main Apache configuration file, httpd.conf, and look for the tags that reference your web server root These tags should look something like this: 16 TEAM LinG 360 How to Do Everything with PHP. .. 352 How to Do Everything with PHP & MySQL form needs to be prefilled with the data for that news item Once the user changes the data and submits the form, the script has to execute an UPDATE query using the record identifier to save the changes to the database This sounds like a lot of work and it is! Here’s the first part of the listing: < ?php. .. like that shown in Figure 16-4 Now, once the administrator enters data into this form and submits it, the same script is called again to process the data (note the presence of the special $_SERVER[ 'PHP_ SELF'] variable in the form’s ACTION attribute) Because the $submit variable will now exist, control will transfer to the latter half of the script 16 TEAM LinG 348 How to Do Everything with PHP & MySQL... deletion Editing News Items The last task on the to- do list involves updating, or editing, a news item The script that does this is called edit .php, and it’s a combination of both add .php and delete .php Like delete .php, edit .php also receives the record’s unique identifier via the $id variable It now needs to display a form similar to that used by add .php, except this 16 FIGURE 16-6 Successful deletion... administration module and manipulating your MySQL database without your knowledge 16 Summary As you can see, building a simple publishing system with PHP and MySQL is extremely easy The two technologies, combined together, are so powerful that putting together dynamic, robust web applications, like the one just described, TEAM LinG 362 How to Do Everything with PHP & MySQL is a snap They’re also great for rapid... discussion of list .php a few pages back, that the script delete .php is passed a $id variable, which holds the unique record identifier for TEAM LinG 350 How to Do Everything with PHP & MySQL the selected news item This identifier is used by delete .php to delete the selected record from the database The next listing illustrates this: < ?php // includes... LinG 354 How to Do Everything with PHP & MySQL else { // form submitted // start processing it } ?> Using the identifier provided by list .php, edit .php queries the database for the fields relevant to that particular record and uses that information to prefill an HTML form Figure 16-7 illustrates what this form might look like FIGURE 16-7 A form to edit news... http://www.melonfire.com/community/ columns/trog/article .php? id=115 ■ More articles and tutorials on PHP, at http://www.melonfire.com/ community/columns/trog/archives .php? category =PHP You’ve now reached the end of this book I hope you now have a clearer idea of what you can do with PHP and MySQL, both individually and together I also hope you feel you have the grounding you need to go out there and begin creating dynamic . 334 How to Do Everything with PHP & MySQL HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter 16 HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter. PM TEAM LinG 336 How to Do Everything with PHP & MySQL HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter 16 HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter. PM TEAM LinG 338 How to Do Everything with PHP & MySQL HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter 16 HowTo8 (8) / How to Do Everything with PHP & MySQL/Vaswani/225795-4/Chapter

Ngày đăng: 07/07/2014, 03:20

Xem thêm: How to do everything with PHP (phần 8) docx

TỪ KHÓA LIÊN QUAN