Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 30 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
30
Dung lượng
648,66 KB
Nội dung
Chapter 4: Using Tables to Display Data 121 How It Works First, the script used the ALTER TABLE command to add the appropriate fields to the existing movie table, and then it used the UPDATE command to insert the new data into those fields. If you aren ’ t familiar with these commands, you should consider reviewing Chapter 3 again. Now that you have the data in place, you need to create a new page that you ’ ll use to display the extra movie information ( movie_details.php ). T ry It Out Displaying Movie Details In this exercise, you ’ ll create a new page to display the data you added in the previous exercise. 1. Open your text editor, and type the following program: < ?php // take in the id of a director and return his/her full name function get_director($director_id) { global $db; $query = ‘SELECT people_fullname FROM people WHERE people_id = ‘ . $director_id; $result = mysql_query($query, $db) or die(mysql_error($db)); $row = mysql_fetch_assoc($result); extract($row); return $people_fullname; } // take in the id of a lead actor and return his/her full name function get_leadactor($leadactor_id) { global $db; $query = ‘SELECT people_fullname FROM people WHERE people_id = ‘ . $leadactor_id; $result = mysql_query($query, $db) or die(mysql_error($db)); $row = mysql_fetch_assoc($result); extract($row); c04.indd 121c04.indd 121 12/10/08 5:45:20 PM12/10/08 5:45:20 PM Part I: Movie Review Web Site 122 return $people_fullname; } // take in the id of a movie type and return the meaningful textual // description function get_movietype($type_id) { global $db; $query = ‘SELECT movietype_label FROM movietype WHERE movietype_id = ‘ . $type_id; $result = mysql_query($query, $db) or die(mysql_error($db)); $row = mysql_fetch_assoc($result); extract($row); return $movietype_label; } // function to calculate if a movie made a profit, loss or just broke even function calculate_differences($takings, $cost) { $difference = $takings - $cost; if ($difference < 0) { $color = ‘red’; $difference = ‘$’ . abs($difference) . ‘ million’; } elseif ($difference > 0) { $color =’green’; $difference = ‘$’ . $difference . ‘ million’; } else { $color = ‘blue’; $difference = ‘broke even’; } return ‘ < span style=”color:’ . $color . ‘;” > ’ . $difference . ‘ < /span > ’; } //connect to MySQL $db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_select_db(‘moviesite’, $db) or die(mysql_error($db)); // retrieve information $query = ‘SELECT movie_name, movie_year, movie_director, movie_leadactor, movie_type, movie_running_time, movie_cost, movie_takings FROM movie WHERE c04.indd 122c04.indd 122 12/10/08 5:45:21 PM12/10/08 5:45:21 PM Chapter 4: Using Tables to Display Data 123 movie_id = ‘ . $_GET[‘movie_id’]; $result = mysql_query($query, $db) or die(mysql_error($db)); $row = mysql_fetch_assoc($result); $movie_name = $row[‘movie_name’]; $movie_director = get_director($row[‘movie_director’]); $movie_leadactor = get_leadactor($row[‘movie_leadactor’]); $movie_year = $row[‘movie_year’]; $movie_running_time = $row[‘movie_running_time’] .’ mins’; $movie_takings = $row[‘movie_takings’] . ‘ million’; $movie_cost = $row[‘movie_cost’] . ‘ million’; $movie_health = calculate_differences($row[‘movie_takings’], $row[‘movie_cost’]); // display the information echo < < < ENDHTML < html > < head > < title > Details and Reviews for: $movie_name < /title > < /head > < body > < div style=”text-align: center;” > < h2 > $movie_name < /h2 > < h3 > < em > Details < /em > < /h3 > < table cellpadding=”2” cellspacing=”2” style=”width: 70%; margin-left: auto; margin-right: auto;” > < tr > < td > < strong > Title < /strong > < /strong > < /td > < td > $movie_name < /td > < td > < strong > Release Year < /strong > < /strong > < /td > < td > $movie_year < /td > < /tr > < tr > < td > < strong > Movie Director < /strong > < /td > < td > $movie_director < /td > < td > < strong > Cost < /strong > < /td > < td > $$movie_cost < td/ > < /tr > < tr > < td > < strong > Lead Actor < /strong > < /td > < td > $movie_leadactor < /td > < td > < strong > Takings < /strong > < /td > < td > $$movie_takings < td/ > < /tr > < tr > < td > < strong > Running Time < /strong > < /td > < td > $movie_running_time < /td > < td > < strong > Health < /strong > < /td > < td > $movie_health < td/ > < /tr > < /table > < /div > < /body > < /html > ENDHTML; ? > c04.indd 123c04.indd 123 12/10/08 5:45:21 PM12/10/08 5:45:21 PM Part I: Movie Review Web Site 124 2. Save it as movie_details.php , and upload it to the web server. 3. Open table3.php in your browser, and click on one of the movie links. It will open movie_details.php , and you will see something like Figure 4 - 6 . Figure 4-6 How It Works Three of the four custom functions at the start of the script should be familiar to you: get_director() , get_leadactor() , and get_movietype() . Each accepts an id key and translates it into the corresponding human - friendly value by performing a database lookup in the appropriate table. In effect, you can think of functions as tiny custom programs that exist within a larger script — they take in some information, process it, and return some result. The fourth custom function, calculate_differences() , generates an HTML string to show whether a movie made a profit, lost money, or broke even. It accepts the movie ’ s takings and the production cost, then subtracts the cost from the takings to find the difference. An if statement is used to further refine the output. If the movie lost money, then the difference will be negative, so the first block of code sets the color to red and trims the leading negative sign by converting the difference to its absolute value with abs() . If the difference is positive, then the movie made money, and the amount will be set in green. The final clause sets the color blue in case the movie broke even financially. The script connects to the database and retrieves the movie information from the movie table. The WHERE clause of the query will make sure that this information is for the requested movie, because it compares the movie_id field with the value passed in to this script through the URL. You ’ ll notice, c04.indd 124c04.indd 124 12/10/08 5:45:21 PM12/10/08 5:45:21 PM Chapter 4: Using Tables to Display Data 125 though, that this time you didn ’ t use extract() to retrieve the field information after the query. Instead, you ’ re assigning them directly from the $row array into variables of their own. This is because you ’ re not using the values as they are, but rather appending ‘ mins ’ to the running time and ‘ million ’ to the amounts. Then the calculate_differences() function is called, and the returned HTML code is saved as $movie_health . After that, the information is displayed back to the user in an HTML - formatted table, using echo and heredoc syntax. A Lasting Relationship What if you wanted to find all the reviews for a particular movie? As it stands, you ’ d need to create a new SQL query in the movies_details.php page and execute it when the page loaded, which would make a total of two SQL queries in one page. It would work, but it would not be very efficient. (We ’ re all efficient coders, aren ’ t we?) This also results in unnecessary code. It ’ s time to answer the question: What ’ s a relationship? A relationship is a way of joining tables so that you can access the data in all those tables. The benefit of MySQL is that it is a relational database and, as such, supports the creation of relationships between tables. When used correctly (this can take a bit of time to get your head around), relationships can be very, very powerful and can be used to retrieve data from many, many tables in one SQL query. The best way to demonstrate this is to build upon what you have done so far, so let ’ s do it. Try It Out Creating and Filling a Movie Review Table Before you can access movie reviews in your movie review table, you need to create the table and then fill it with data. 1. Open your text editor, and type the following code: < ?php $db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_select_db(‘moviesite’, $db) or die(mysql_error($db)); //create the reviews table $query = ‘CREATE TABLE reviews ( review_movie_id INTEGER UNSIGNED NOT NULL, review_date DATE NOT NULL, reviewer_name VARCHAR(255) NOT NULL, review_comment VARCHAR(255) NOT NULL, review_rating TINYINT UNSIGNED NOT NULL DEFAULT 0, KEY (review_movie_id) ) ENGINE=MyISAM’; c04.indd 125c04.indd 125 12/10/08 5:45:21 PM12/10/08 5:45:21 PM Part I: Movie Review Web Site 126 mysql_query($query, $db) or die (mysql_error($db)); //insert new data into the reviews table $query = < < < ENDSQL INSERT INTO reviews (review_movie_id, review_date, reviewer_name, review_comment, review_rating) VALUES (1, “2008-09-23”, “John Doe”, “I thought this was a great movie Even though my girlfriend made me see it against my will.”, 4), (1, “2008-09-23”, “Billy Bob”, “I liked Eraserhead better.”, 2), (1, “2008-09-28”, “Peppermint Patty”, “I wish I’d have seen it sooner!”, 5), (2, “2008-09-23”, “Marvin Martian”, “This is my favorite movie. I didn’t wear my flair to the movie but I loved it anyway.”, 5), (3, “2008-09-23”, “George B.”, “I liked this movie, even though I Thought it was an informational video from my travel agent.”, 3) ENDSQL; mysql_query($query, $db) or die(mysql_error($db)); echo ‘Movie database successfully updated!’; ? > 2. Save this file as db_ch04 - 2.php , and open it in your browser. Your reviews table has now been created as well as populated. How It Works By now you should be familiar with creating tables using MySQL and PHP, so this should be pretty self - explanatory. If you ’ re having trouble, you might want to go back and review the relevant sections in Chapter 3 . Try It Out Displaying the Reviews In this example, you ’ re going to link two tables (movies and reviews) and show the reviews for a particular movie. This requires a lot of changes to the movie_details.php page, so you would be best served by making a backup copy of the file, as you can ’ t ever be too careful. If you make any mistakes, then you can always revert back to your original version. To display the reviews, follow these steps: 1. Add this code to the top of movie_details.php : // function to generate ratings function generate_ratings($rating) { $movie_rating = ‘’; for ($i = 0; $i < $rating; $i++) { $movie_rating .= ‘ < img src=”star.png” alt=”star”/ > ’; } return $movie_rating; } c04.indd 126c04.indd 126 12/10/08 5:45:22 PM12/10/08 5:45:22 PM Chapter 4: Using Tables to Display Data 127 2. Now split the tail end of the heredoc block that outputs the movie ’ s information so that there are two: < td > < strong > Health < /strong > < /td > < td > $movie_health < td/ > < /tr > < /table > ENDHTML; echo < < < ENDHTML < /div > < /body > < /html > ENDHTML; 3. Add this code between the two heredoc blocks to fill the break you just made: // retrieve reviews for this movie $query = ‘SELECT review_movie_id, review_date, reviewer_name, review_comment, review_rating FROM reviews WHERE review_movie_id = ‘ . $_GET[‘movie_id’] . ‘ ORDER BY review_date DESC’; $result = mysql_query($query, $db) or die(mysql_error($db)); // display the reviews echo < < < ENDHTML < h3 > < em > Reviews < /em > < /h3 > < table cellpadding=”2” cellspacing=”2” style=”width: 90%; margin-left: auto; margin-right: auto;” > < tr > < th style=”width: 7em;” > Date < /th > < th style=”width: 10em;” > Reviewer < /th > < th > Comments < /th > < th style=”width: 5em;” > Rating < /th > < /tr > ENDHTML; while ($row = mysql_fetch_assoc($result)) { $date = $row[‘review_date’]; $name = $row[‘reviewer_name’]; $comment = $row[‘review_comment’]; $rating = generate_ratings($row[‘review_rating’]); c04.indd 127c04.indd 127 12/10/08 5:45:22 PM12/10/08 5:45:22 PM Part I: Movie Review Web Site 128 echo < < < ENDHTML < tr > < td style=”vertical-align:top; text-align: center;” > $date < /td > < td style=”vertical-align:top;” > $name < /td > < td style=”vertical-align:top;” > $comment < /td > < td style=”vertical-align:top;” > $rating < /td > < /tr > ENDHTML; } 4. Save the file as movie_details.php (overwriting the existing one — we hope you have made a backup copy, as suggested). 5. Upload the file to your web server, load table3.php , and click a movie. You ’ ll see something similar to Figure 4 - 7 . Figure 4-7 How It Works The generate_ratings() function is fairly straightforward. You send it the value that is in the ratings field for a movie, and it creates an HTML string of rating images for that movie and returns it. Notice that you are using .= to ensure that movies with a rating of more than 1 will get additional images added to the single rating image. c04.indd 128c04.indd 128 12/10/08 5:45:22 PM12/10/08 5:45:22 PM Chapter 4: Using Tables to Display Data 129 By splitting the heredoc block into two sections, you made room to insert the HTML code that displays the reviews without breaking your page layout. The first portion displays the opening HTML tags and the details table, while the second portion displays the closing tags for the page. The MySQL query retrieves all the reviews for the movie with the appropriate review_movie_id . The ORDER BY phrase of the query instructs MySQL to sort the results first in chronologically descending order. After that, the fields are extracted from the result set and displayed as a row in the table. You ’ ve made quite a few changes in this section. But, as you can see, the changes have been well worth it. Now you know how to use MySQL to create relationships between tables. You successfully retrieved all the reviews from the review table, depending on the movie_id variable. You also looked at using the $_GET superglobal array to pass values from one page to another. Summary You ’ ve learned how to work with HTML tables to display your data, how to pull data from more than one database table and have it displayed seamlessly with data from another table, and how to create dynamic pages that display detailed information about the rows in your database. You can also include images to graphically display data to your web site visitors, as with this chapter ’ s example of using rating stars. So far, you ’ ve hard - coded all the additions to the database yourself, which isn ’ t very dynamic. In Chapter 6 , we ’ ll teach you how to let the user add items to the database and edit them. But first, you need to know how to use forms with PHP, which is the subject of our next chapter. Exercises 1. Add an entry in the top table of your movie_details.php file that shows the average rating given by reviewers. 2. Change each column heading of the reviews table in your movie_details.php to a link that allows the user to sort by that column (i.e., the user would click on “ Date ” to sort all the reviews by date). 3. Alternate the background colors of each row in the review table of your movie_details.php file to make them easier to read. Hint: odd - numbered rows would have a background of one color, even - numbered rows would have a background of another color. c04.indd 129c04.indd 129 12/10/08 5:45:23 PM12/10/08 5:45:23 PM c04.indd 130c04.indd 130 12/10/08 5:45:23 PM12/10/08 5:45:23 PM [...]... yourself with forms Let’s start with the HTML form itself You can find HTML references at the World Wide Web Consortium web site at www.w3.org/MarkUp FORM Element First, we’ll introduce the first HTML element you’ll need: form It delimits the form’s area in the page and holds the fields you want your web site users to fill in ...5 Form Elements: Letting the User Work with Data An interactive web site requires user input, which is generally gathered through forms As in the paper-based world, the user fills in a form and submits its content for processing In a web application, the processing isn’t performed by a sentient being; rather, it is performed by a PHP script Thus, the... (isset($_POST[‘debug’])) { echo ‘’; print_r($_POST); echo ‘’; } ?> 4 Open form4.php in your web browser The new form is displayed, shown in Figure 5-7, which prompts the visitor for more details Figure 5-7 149 c05.indd 149 12/10/08 5:45:43 PM Part I: Movie Review Web Site 5 Enter the name of the movie you want to add: Grand Canyon 6 Click the Add button; this takes you to the... Data Figure 5-1 You can see two distinct parts on the resulting page: the “Hello Test” portion and the DEBUG part shown in Figure 5-2 Figure 5-2 133 c05.indd 133 12/10/08 5:45:37 PM Part I: Movie Review Web Site Congratulations, you just coded your first form-processing script How It Works As with any good recipe, it’s an excellent idea to start working on forms by understanding the ingredients you will... build a simple application that allows you to add, edit, or delete members of a data set (in this instance, the data will be movies, actors, and directors) This chapter welcomes you into a world of PHP /MySQL interaction by covering the following: ❑ Creating forms using buttons, text boxes, and other form elements ❑ Creating PHP scripts to process HTML forms ❑ Passing hidden information to the form-processing... multiple items Drop-down list boxes and radio buttons allow for one selection only Check boxes and multiline list boxes provide for multiple choices 135 c05.indd 135 12/10/08 5:45:38 PM Part I: Movie Review Web Site Try It Out Limiting the Input Choice Let’s start with the simple type of input Follow these steps to create a single-selection list: 1 Create a text file named form2.html, and open it in your... and click the Submit button The display page that appears, shown in Figure 5-4, is rather simple; it holds only debug information and a greeting 137 c05.indd 137 12/10/08 5:45:39 PM Part I: Movie Review Web Site Figure 5-4 How It Works As you see, this code uses logic similar to that in formprocess1.php Two fields have been added (a drop-down list box and a check box) formprocess2.php does the same thing... Movie Actor 139 c05.indd 139 12/10/08 5:45:40 PM Part I: Movie Review Web Site Director Display Debug info . //connect to MySQL $db = mysql_ connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_ select_db(‘moviesite’, $db) or die (mysql_ error($db)); . < ?php $db = mysql_ connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_ select_db(‘moviesite’, $db) or die (mysql_ error($db)); . movietype_label FROM movietype WHERE movietype_id = ‘ . $type_id; $result = mysql_ query($query, $db) or die (mysql_ error($db)); $row = mysql_ fetch_assoc($result); extract($row); return $movietype_label; }