Chapter 4: Using Tables to Display Data 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 UPDA
Trang 1Chapter 4: Using Tables to Display Data
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 namefunction 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 namefunction 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);
Trang 2
Part I: Movie Review Web Site
// function to calculate if a movie made a profit, loss or just broke even
function calculate_differences($takings, $cost) {
$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
Trang 3Chapter 4: Using Tables to Display Data
$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 informationecho < < < ENDHTML
Trang 4Part 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,
Trang 5Chapter 4: Using Tables to Display Data
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:
$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’;
Trang 6Part I: Movie Review Web Site
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)
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;
}
Trang 7Chapter 4: Using Tables to Display Data
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 >
/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 reviewsecho < < < ENDHTML < h3 > < em > Reviews < /em > < /h3 >
< tr >
< th style=”width: 7em;” > Date < /th >
< th style=”width: 10em;” > Reviewer < /th >
$name = $row[‘reviewer_name’];
$comment = $row[‘review_comment’];
$rating = generate_ratings($row[‘review_rating’]);
Trang 8
Part I: Movie Review Web Site
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
Trang 9Chapter 4: Using Tables to Display Data
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
Summar y
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
Trang 115
For m Elements: Letting the
User Wor k 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 script requires some sort of coded intelligence
When you fill in a paper form, you generally use a means to deliver its content (the postal service
is one example) to a known address (such as a mail - order bookstore) The same logic applies to online forms The data from an HTML form is sent to a specific location and processed
The form element is rather simple in HTML It states where and how it will send the contents of the elements it contains once submitted It is after that point that PHP comes into play PHP uses a set of simple yet powerful expressions that, when combined, provide you with the means to do virtually anything you want The PHP script receives the data from the form and uses it to perform an action such as updating the contents of a database, sending an e - mail, testing the data format, and so on
In this chapter, you begin to 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 script via hidden form controls and a URL query string
Your F irst Form
As a wise man once said, “ Every journey starts with a single step ” To start this particular journey, you will focus on a very simple form It will include only a text field and a submit button The processing script will display only the value entered in the text field
❑
❑
❑
Trang 12Part I: Movie Review Web Site
132
Try It Out Say My Name
In this exercise, you are going to get PHP to respond to a name entered in a form This is a simple
variation of the commonly used “ hello world ” program, allowing you to take your first step into
interactivity
1 Create form1.html with your favorite text editor
2 Enter the following code:
< td colspan=”2” style=”text-align: center;” >
< input type=”submit” name=”submit” value=”Submit” / > < /td >
4 Open form1.html in your browser
5 Type your name in the name text box (as shown in Figure 5 - 1 ), and click the Submit button
Trang 13Chapter 5: Form Elements: Letting the User Work with Data
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-1
Figure 5-2
Trang 14Part I: Movie Review Web Site
134
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 be using You ’ ll need some background information about HTML form elements
and a few PHP functions to familiarize 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
< form action=”formprocess1.php” method=”post” >
< ! form controls go here >
< /form >
Notice that the form element has an ending tag and two attributes The first attribute ( action ) is the
recipient page address (the form - processing script) The second attribute ( method ) is the way in which
you will send the data to the recipient You may recall that there are two separate ways of sending a form
to its processing script: the POST and the GET methods
The POST method takes the data from the form fields and sends it through an HTTP header In this
case, the data cannot be seen in the URL The GET method gets the data from the form fields, encodes it,
and appends it to the destination URL
INPUT Element
The second new HTML element included here is input This is the basis of most forms and can be
used in many different ways to gather many different types of information In this case, you use two
different types of input : the text and submit types
Here ’ s the input text type:
< input type=”text” name=”name” / >
The input text type is a standard single - line text box As with all form controls, it needs a name so
that the processing script can access its content using the following syntax:
< ?php
echo $_POST[‘name’]; // will display the value typed in
?
Trang 15Chapter 5: Form Elements: Letting the User Work with Data
And here ’ s the input submit type:
< input type=”submit” name=”submit” value=”Submit” / >
As its name cleverly hints, the submit element displays a button that causes the browser to submit the form when it is pressed The button ’ s text is set through the value attribute As mentioned for the text
input , this form control needs a name for a processing reference
Processing the Form
In this little script, you may have noticed a few new functions and some new syntax, and you are probably curious about them
The first form - processing script is an interactive variation of the famous “ hello world, ” but in this case it displays “ hello ” and the name you type in the text box To make this happen, you need to print the value
of the text field you filled in on the form You know the echo command, so let ’ s move on to the other piece, $_POST[‘name’]
The $_POST global array contains all form data submitted with the POST method The array index of the field is its name In a moment, you ’ ll see how to check the content of your $_POST array using the
print_r() function
< ?phpecho ‘ < h1 > Hello ‘ $_POST[‘name’] ‘! < /h1 > ’;? >
In this example, $_POST[‘name’] displays what you entered in the name field
You might wonder what print_r($_POST) does It simply dumps the whole contents of the super global $_POST array to the output This is a great way to debug your forms The $_POST array, as with all arrays, has case - sensitive indexes Use this tip to check for case and display the state of your objects when building a script
When receiving the submitted form information, PHP sets the $_POST array with the data that the form sends As with any array, you can directly access any of the indexes by name In this instance, you can clearly see that the name index contains the value Joe This trick works for all forms, even the most complicated ones
Let ’ s move on to see how you can use more HTML elements during form input to interact with the user
Driving the User Input
The form in this example allows you to lead the user to choose values from a set of values you provide Defining a value set is done through the use of specific HTML elements, such as list boxes, radio buttons, and check boxes
Two kinds of predefined user input are in HTML forms The first kind allows you to choose one item from the available options; the second allows the user to choose multiple items Drop - down list boxes and radio buttons allow for one selection only Check boxes and multiline list boxes provide for multiple choices