Tải bản đầy đủ (.pdf) (30 trang)

Beginning PHP6, Apache, MySQL Web Development- P5 potx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (660.95 KB, 30 trang )

Chapter 3: Using PHP with My SQL
91
Querying the Database
Now that you have some data in the database, you probably want to retrieve it. You use the SELECT
statement to choose data that fits your criteria.
Typical syntax for this command is as follows:

SELECT [
field names
]
AS [
alias
]
FROM [
tablename
]
WHERE [
criteria
]
ORDER BY [
fieldname to sort on
] [ASC|DESC]
LIMIT [
offset
,
maxrows
]

You can set numerous other parameters, but these are the most commonly used:

SELECT [field names] : First decide what specific field names you want to retrieve. If you


want to see them all, you can use
* in place of the field names.

AS : You use alias field names so that you can reference them later as different names. An
example would be:

SELECT movie_name, movie_year AS relase_year FROM movie

FROM : You need to name the table or tables from which you are pulling the data.

WHERE : List your criteria for filtering out the data, as described in the following section.

ORDER BY : Use this parameter if you want the data sorted on a particular field. The results are
returned in ascending order by default, though you can explicitly request ascending order with

ASC . If you want the results returned in descending order, use DESC .

LIMIT : This enables you to limit the number of results returned and offset the first record
returned to whatever number you choose. An example would be:

LIMIT 9, 10

This would show records 10 through 19. This is a useful feature for pagination (showing only a certain
number of records on a page and then allowing the user to click a Next page link to see more).
For a complete reference, we refer you to the official documentation at
www.mysql.com .
WHERE , oh WHERE
The beast clause called WHERE deserves its own little section because it ’ s really the meat of the query.
(No offense to the other clauses, but they are pretty much no brainers.)
WHERE is like a cool big brother

who can really do some interesting stuff. While
SELECT tells MySQL which fields you want to see, WHERE
tells it which records you want to see. It is used as follows:

// retrieves all information about all customers
SELECT * FROM customers;

// retrieves all information about male customers
SELECT * FROM customers WHERE gender = “Male”







c03.indd 91c03.indd 91 12/10/08 5:46:09 PM12/10/08 5:46:09 PM
92
Part I: Movie Review Web Site
Let ’ s look at the WHERE clause in a little more detail:
Comparison operators are the heart of a
WHERE clause and include the following:
❑ = is used to test if two values are equal
❑ != is used to test if two values are not equal
❑ < is used to test if one value is less than the second
❑ < = is used to test if one value is less than or equal to the second
❑ > is used to test if one value is greater than the second
❑ > = is used to test if one value is greater than or equal to the second
❑ LIKE lets you compare text and allows you to use % and _ as wildcards. Wildcards allow
you to search even if you know a piece of what ’ s in the field but don ’ t know the entire

value, or you don ’ t want an exact match. For example:

SELECT * FROM products WHERE description LIKE “%shirt%”

❑ The WHERE clause in this query matches any records that have the text pattern “ shirt ” in
the description column, such as “ t - shirt, ” “ blue shirts, ” or “ no shirt, no shoes, no service. ”
Without the
% wildcard, you would have those products that have a description of just
“ shirt ” returned, and nothing else.
Logical operators such as
AND , NOT , OR , and XOR are also accepted in the WHERE clause:
SELECT * FROM products WHERE description LIKE “%shirt%” AND price < = 24.95

This gives you all the products that have the word or text pattern of “ shirt ” in the description
and that have a price of less than or equal to $24.95.
Now that you understand how a
SELECT query is written, let ’ s look at it in action, shall we?
Try It Out Using the SELECT Query
In this exercise, you ’ ll create a short script that demonstrates how the SELECT query works.
1. Open your text editor, and type this 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));

// select the movie titles and their genre after 1990
$query = ‘SELECT
movie_name, movie_type
FROM
movie

WHERE


c03.indd 92c03.indd 92 12/10/08 5:46:09 PM12/10/08 5:46:09 PM
Chapter 3: Using PHP with My SQL
93
movie_year > 1990
ORDER BY
movie_type’;
$result = mysql_query($query, $db) or die(mysql_error($db));

// show the results
while ($row = mysql_fetch_array($result)) {
extract($row);
echo $movie_name . ‘ - ‘ . $movie_type . ‘ < br/ > ’;
}
? >
2. Save this file as select1.php , and then run it from your browser.
How It Works
You should see the screen shown in Figure 3 - 1 after running select1.php .
Figure 3-1
First you had to connect to the MySQL server and the specific database. Then you planned out your
query and assigned it to the
$query variable.
c03.indd 93c03.indd 93 12/10/08 5:46:09 PM12/10/08 5:46:09 PM
94
Part I: Movie Review Web Site
You wanted to choose only the movie_name and movie_type fields from the movie table because you
don ’ t care about seeing the rest of the information contained in the table at this time. If you had
wanted to retrieve everything, you simply could have written:


SELECT
movie_id, movie_name, movie_type, movie_year, movie_leadactor, movie_
director
FROM
movie

or even:
SELECT * FROM movie

The WHERE condition in your query limited the results to only movies filmed after 1990. You also asked
the server to sort the results by movie type, with the
ORDER clause.
Then you issued the query to the MySQL server and stored the response in a variable,
$result .
$result = mysql_query($query, $db) or die(mysql_error($db));

Then, you looped through the results with a while loop:
while ($row = mysql_fetch_array($result)) {
extract($row);
echo $movie_name . ‘ - ‘ . $movie_type . ‘ < br/ > ’;
}

You retrieved the row ’ s data as an array named $row for each row in the returned result set, using the

mysql_fetch_array() function. You then extracted all the variables in $row , using the extract()
function to find variables with the same name as the array ’ s keys;
echo ed out what you needed; and
then went on to the next row of results from your query. When there were no more rows that matched
your criteria, the

while loop ended.
Pretty easy, eh? Let ’ s try using the
foreach loop instead of the while function, and see how it works.
Working with PHP and Arrays of Data: foreach
The foreach loop is similar to the while loop, if you ’ re using while to loop through a list of results
from your query. Its purpose is to apply a block of statements to every row in your results set. It is used
in this way:

foreach ($row as $value) {
echo $value;
echo ‘ < br > ’;
}

The preceding code would take all the variables in the $row array and list each value, with a line
break in between them. You can see this in action in Chapters 4 and 5 and get a better idea of how it
can be used.
c03.indd 94c03.indd 94 12/10/08 5:46:11 PM12/10/08 5:46:11 PM
Chapter 3: Using PHP with My SQL
95
Try It Out Using foreach
This exercise contrasts foreach with the while you used in the previous exercise.
1. In your select1.php file, make the following highlighted changes:
< ?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));

// select the movie titles and their genre after 1990
$query = ‘SELECT
movie_name, movie_type

FROM
movie
WHERE
movie_year > 1990
ORDER BY
movie_type’;
$result = mysql_query($query, $db) or die(mysql_error($db));

// show the results
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $value) {
echo $value . ‘ ‘;
}
echo ‘ < br/ > ’;
}
? >

How It Works
You should see the same results as before, except that there is now no dash between the elements.
Pretty sneaky, huh?
mysql_fetch_array actually returns two sets of arrays (one with associative
indices, one with numerical indices), so you see duplicate values if you use
foreach without first
isolating one of the arrays. You can do this by using either
mysql_fetch_array($result, MYSQL_
ASSOC)
or mysql_fetch_assoc($result) to perform the same thing and return only one of the
arrays. You still need to use the
while function to proceed through the selected rows one at a time, but
you can see that using

foreach applies the same sets of commands to each value in the array,
regardless of their contents.
Sometimes you will need to have more control over a specific value, and therefore you can ’ t apply the
same formatting rules to each value in the array, but the
foreach function can also come in handy
when using formatting functions, such as creating tables. In the following exercise, you ’ ll create
another version of the
select1.php program that illustrates this.
c03.indd 95c03.indd 95 12/10/08 5:46:12 PM12/10/08 5:46:12 PM
96
Part I: Movie Review Web Site
Try It Out Using foreach to Create a Table
In this exercise, you ’ ll use foreach to apply some formatting rules to the results of your query.
1. Open your text editor, and enter the following script:
< ?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));

// select the movie titles and their genre after 1990
$query = ‘SELECT
movie_name, movie_type
FROM
movie
WHERE
movie_year > 1990
ORDER BY
movie_type’;
$result = mysql_query($query, $db) or die(mysql_error($db));


// show the results
echo ‘ < table border=”1” > ’;
while ($row = mysql_fetch_assoc($result)) {
echo ‘ < tr > ’;
foreach ($row as $value) {
echo ‘ < td > ’ . $value . ‘ < /td > ’;
}
echo ‘ < /tr > ’;
}
echo ‘ < /table > ’;
? >
2. Save this script as select2.php , and then open it in your browser. You should see something
like Figure 3 - 2 .
c03.indd 96c03.indd 96 12/10/08 5:46:12 PM12/10/08 5:46:12 PM
Chapter 3: Using PHP with My SQL
97
Figure 3-2
How It Works
You used the mysql_query() function and while loop to retrieve your desired records and fields.
Then for each value you retrieved, you placed it in a separate table cell, using a
foreach loop.
You can see that this script would easily output a long string of array variables with a few lines of
code, whereas if you had to echo out each separate variable with the accompanying HTML code, this
script would be quite lengthy.
A Tale of Two Tables
The preceding code is all nice and neat and pretty, but it doesn ’ t do you a whole lot of good if you don ’ t have
a secret decoder ring to tell you what those cryptic “ movie type ” numbers correspond to in plain English.
That information is all stored in a separate table, the
movietype table. So how do you get this information?
You can get information from more than one table in two ways:

Reference the individual tables in your query and link them temporarily through a common field.
Formally
JOIN the individual tables in your query.
Let ’ s try out these methods and then talk about each of them in more detail.


c03.indd 97c03.indd 97 12/10/08 5:46:12 PM12/10/08 5:46:12 PM
98
Part I: Movie Review Web Site
Referencing Two Tables
You can distinguish between two tables in your database by referencing them in the SELECT statement,
as follows:

// retrieves customers’ names from customers table and order_total from
// orders table where the cust_ID field in the customers table equals the
// cust_ID field in the orders table.

SELECT
customers.name, orders.order_total
FROM
customers, orders
WHERE
customers.cust_ID = orders.cust_ID

If a customer ’ s ID is 123, you will see all the order_totals for all the orders for that specific customer,
enabling you to determine all the money customer 123 has spent at your store.
Although you are linking the two tables through the
cust_ID field, the names do not have to be the
same. You can compare any two field names from any two tables. An example would be:


// retrieves customers’ names from customers table and order_total from
// orders table where the email field in the customers table equals the
// shiptoemail field in the orders table.
SELECT
customers.name, orders.order_total
FROM
customers, orders
WHERE
customers.email = orders.shiptoemail


This would link your tables through the email and shiptoemail fields from different tables.
Try It Out Referencing Individual Tables
This exercise will show you how to reference multiple tables in your query.
1. Change your select2.php program as shown here (changes are highlighted):
< ?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));

// select the movie titles and their genre after 1990
$query = ‘SELECT
movie.movie_name, movietype.movietype_label
FROM
movie, movietype
WHERE
c03.indd 98c03.indd 98 12/10/08 5:46:13 PM12/10/08 5:46:13 PM
Chapter 3: Using PHP with My SQL
99
movie.movie_type = movietype.movietype_id AND

movie_year > 1990
ORDER BY
movie_type’;
$result = mysql_query($query, $db) or die(mysql_error($db));

// show the results
echo ‘ < table border=”1” > ’;
while ($row = mysql_fetch_assoc($result)) {
echo ‘ < tr > ’;
foreach ($row as $value) {
echo ‘ < td > ’ . $value . ‘ < /td > ’;
}
echo ‘ < /tr > ’;
}
echo ‘ < /table > ’;
? >

2. Save your script and run it. Your screen should look something like Figure 3 - 3 .
Figure 3-3
c03.indd 99c03.indd 99 12/10/08 5:46:13 PM12/10/08 5:46:13 PM
100
Part I: Movie Review Web Site
How It Works
Now you can see a table with the movie names and actual words for the type of movie, instead of
your cryptic code, as was the case in Figure 3 - 2 . The common fields were linked in the
WHERE portion
of the statement. ID numbers from the two different tables (fieldname
movie_type in the movie table
and fieldname
movietype_id in the movietype table) represented the same thing, so that ’ s where

you linked them together.
Joining Two Tables
In life as in code, regardless of the circumstances under which two things join together, it is rarely a
simple thing. More often than not, it comes with conditions and consequences.
In the world of MySQL, joins are also complex things. We will discuss joins in greater detail in Chapter
10 ; meanwhile, we walk you through a very simple and commonly used
join so you can get a taste of
what joining is all about. The
JOIN function gives you greater control over how your database tables
relate to and connect with each other, but it also requires a greater understanding of relational databases
(another topic covered in Chapter 10 ).
Try It Out Joining Two Tables
In this exercise, you ’ ll link the two tables with a JOIN .
1. Make the following highlighted changes to select2.php :
< ?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));

// select the movie titles and their genre after 1990
$query = ‘SELECT
movie_name, movietype_label
FROM
movie LEFT JOIN movietype ON movie_type = movietype_id
WHERE
movie.movie_type = movietype.movietype_id AND
movie_year > 1990
ORDER BY
movie_type’;
$result = mysql_query($query, $db) or die(mysql_error($db));


// show the results
echo ‘ < table border=”1” > ’;
c03.indd 100c03.indd 100 12/10/08 5:46:15 PM12/10/08 5:46:15 PM
Chapter 3: Using PHP with My SQL
101
while ($row = mysql_fetch_assoc($result)) {
echo ‘ < tr > ’;
foreach ($row as $value) {
echo ‘ < td > ’ . $value . ‘ < /td > ’;
}
echo ‘ < /tr > ’;
}
echo ‘ < /table > ’;
? >

2. Save the script, and open it in your browser.
How It Works
You should see the same result as in the previous example. As you can see, you simply listed all the
fields you wanted to see, regardless of the table they were in (MySQL will find them as long as the
table name is referenced there somewhere). You did this in the first line of the
SELECT statement:
SELECT movie_name, movietype_label

Then you told MySQL what tables you wanted to access and what type of join should be used to bring
them together, in these statements:

FROM
movie LEFT JOIN movietype


You used the LEFT join statement in this case. Although there are other things that go along with this,
the
LEFT join, in layman ’ s terms, simply means that the second table ( movietype in the example) is
dependent on the first table (
movie ). You are getting the main information from movie and looking up
a bit of information from
movietype .
You then told the server which field to use to join them together, with:

ON movie_type = movietype_id

Again, you don ’ t need to clarify which table is being used, but if you have overlapping field names
across tables, you can add this if you like to avoid confusion.
You kept your condition about only showing the movies that were made after 1990, and sorted them
by numerical movie type with these lines:

WHERE
movie.movie_type = movietype.movietype_id AND
movie_year > 1990
ORDER BY
movie_type

And the rest of the code is the same. See, joining wasn ’ t that bad, was it?
c03.indd 101c03.indd 101 12/10/08 5:46:15 PM12/10/08 5:46:15 PM
102
Part I: Movie Review Web Site
Helpful Tips and Suggestions
We all get into a little trouble now and then. Instead of sitting in the corner and sucking your thumb, or
banging your head in frustration against your keyboard, relax! We are here to help.
Documentation

The folks at MySQL have provided wonderfully thorough documentation covering more than you ever
wanted to know about its capabilities, quirks, and plans for the future. We have stated this time and time
again, but the official web site really can provide you with the most up - to - date and accurate information.
You can search the documentation, or even add your own comments if you ’ ve discovered something
especially helpful that might help out other developers just like you. Because this is all open source, you
really do get a community feeling when you read through the documentation.
Once again, you can find the manual at
www.mysql.com .
Using My SQL Query Browser
Now that you ’ ve been given the task of learning MySQL and PHP on your own from scratch, we ’ re
going to let you in on a dirty little secret called MySQL Query Browser. MySQL Query Browser is
another wonderful open source project that enables you to access your MySQL databases through a GUI
desktop application. It ’ s easy to install and manage, and it makes administering your tables and data a
breeze. It does have some limitations, but for the most part it will make you a lot more efficient.
With this software, you can easily do the following:
Drop and create databases
Create, edit, and delete tables
Create, edit, and delete fields
Enter any MySQL statements
View and print table structure
Generate PHP code
View data in table format
You can download the software by visiting

gui - tools/5.0.html
. MySQL Query Browser is part of the MySQL Tools package. Figure 3 - 4
shows what MySQL Query Browser looks like.








c03.indd 102c03.indd 102 12/10/08 5:46:15 PM12/10/08 5:46:15 PM
Chapter 3: Using PHP with My SQL
103
Summary
We ’ ve covered some pretty fundamental programming concepts in this chapter, and we ’ ll delve more
into them in future chapters. But for now you should have a pretty good handle on the basics.
You should have a good understanding of databases and tables, and know how to insert data and
retrieve stored information from those tables. You should also have a good understanding of how
MySQL works with PHP to make dynamic pages in your web site.
In the next few chapters, you will build on this knowledge to create more complex applications.
Exercises
We have started you on the MySQL/PHP journey, and in the next few chapters we take you places
you ’ ve never dreamed of. To fine - tune your skills, here are a few exercises to make sure you really know
your stuff:
1. Create a PHP program that prints the lead actor and director for each movie in the database.
2. Pick only comedies from the movie table, and show the movie name and the year it was
produced. Sort the list alphabetically.
3. Show each movie in the database on its own page, and give the user links in a “ page 1, page 2,
page 3 ” – type navigation system. Hint: Use
LIMIT to control which movie is on which page.

Figure 3-4
c03.indd 103c03.indd 103 12/10/08 5:46:15 PM12/10/08 5:46:15 PM
c03.indd 104c03.indd 104 12/10/08 5:46:17 PM12/10/08 5:46:17 PM
4
Using Tables to Display Data

Now that you can successfully marry PHP and MySQL to produce dynamic pages, what happens
when you have rows and rows of data that you need to display? You need to have some
mechanism for your viewers to easily read the data, and it needs to be presented in a nice, neat,
organized fashion. The easiest way to do this is to use tables.
This chapter covers the following:
Creating a table to hold the data from the database .
Creating column headings automatically .
Populating the table with the results of a basic MySQL query .
Populating the table with the results of more complex MySQL queries .
Making the output user - friendly .
Creating a Table
Before you can list your data, you need to set up the structure, column headings, and format of
your HTML table. This way, your data has some place to go! The skeleton of this table gives you
the blueprint for how your data will be laid out once it is retrieved from the database.





c04.indd 105c04.indd 105 12/10/08 5:45:14 PM12/10/08 5:45:14 PM
Part I: Movie Review Web Site
106
Try It Out Building a Table
In this exercise, you ’ ll define the table headings for your table and then fill it with data.
1. Open your favorite text/HTML editor, and enter the following code:
< div style=”text-align: center;” >
< h2 > Movie Review Database < /h2 >
< table border=”1” cellpadding=”2” cellspacing=”2”
style=”width: 70%; margin-left: auto; margin-right: auto;” >
< tr >

< th > Movie Title < /th >
< th > Year of Release < /th >
< th > Movie Director < /th >
< th > Movie Lead Actor < /th >
< th > Movie Type < /th >
< /tr >
< /table >
< /div >
2. Save this file as table1.php , and upload it to your Web server.
3. Load your favorite browser and view the page that you have just uploaded. Your table should
look like the one in Figure 4 - 1 .
Figure 4-1
c04.indd 106c04.indd 106 12/10/08 5:45:15 PM12/10/08 5:45:15 PM
Chapter 4: Using Tables to Display Data
107
4. Open the file table1.php in your editor again, and add the code to connect to the database at
the top. We used the database created in Chapter 3 for the purposes of the example here.
Remember to substitute your own values for the server name, username, password, and
database name in the given example, if necessary.

< ?php
//connect to MySQL
$db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or
die (‘Unable to connect. Check your connection parameters.’);

// make sure you’re using the right database
mysql_select_db(‘moviesite’, $db) or die(mysql_error($db));
? >
< div style=”text-align: center;” >
< h2 > Movie Review Database < /h2 >

< table border=”1” cellpadding=”2” cellspacing=”2”
style=”width: 70%; margin-left: auto; margin-right: auto;” >
< tr >
< th > Movie Title < /th >
< th > Year of Release < /th >
< th > Movie Director < /th >
< th > Movie Lead Actor < /th >
< th > Movie Type < /th >
< /tr >
< /table >
< /div >

5. Run a SQL query against the database and get the results. And while you are at it, count how
many records were returned from the query.
< ?php
//connect to MySQL
$db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or
die (‘Unable to connect. Check your connection parameters.’);

// make sure you’re using the right database
mysql_select_db(‘moviesite’, $db) or die(mysql_error($db));

// retrieve information
$query = ‘SELECT
movie_name, movie_year, movie_director, movie_leadactor,
movie_type
FROM
movie
ORDER BY
movie_name ASC,

movie_year DESC’;
$result = mysql_query($query, $db) or die(mysql_error($db));

// determine number of rows in returned result
$num_movies = mysql_num_rows($result);
c04.indd 107c04.indd 107 12/10/08 5:45:16 PM12/10/08 5:45:16 PM
Part I: Movie Review Web Site
108
? >
< div style=”text-align: center;” >
< h2 > Movie Review Database < /h2 >
< table border=”1” cellpadding=”2” cellspacing=”2”
style=”width: 70%; margin-left: auto; margin-right: auto;” >
< tr >
< th > Movie Title < /th >
< th > Year of Release < /th >
< th > Movie Director < /th >
< th > Movie Lead Actor < /th >
< th > Movie Type < /th >
< /tr >
< /table >
< /div >

6. After the closing tr tag but before the closing table tag in the original HTML, enter a while
loop to process through the retrieved records. Then, output the number of movie records after
the closing
table tag.
< ?php
//connect to MySQL
$db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or

die (‘Unable to connect. Check your connection parameters.’);

// make sure you’re using the right database
mysql_select_db(‘moviesite’, $db) or die(mysql_error($db));

// retrieve information
$query = ‘SELECT
movie_name, movie_year, movie_director, movie_leadactor,
movie_type
FROM
movie
ORDER BY
movie_name ASC,
movie_year DESC’;
$result = mysql_query($query, $db) or die(mysql_error($db));

// determine number of rows in returned result
$num_movies = mysql_num_rows($result);
? >
< div style=”text-align: center;” >
< h2 > Movie Review Database < /h2 >
< table border=”1” cellpadding=”2” cellspacing=”2”
style=”width: 70%; margin-left: auto; margin-right: auto;” >
< tr >
< th > Movie Title < /th >
< th > Year of Release < /th >
< th > Movie Director < /th >
< th > Movie Lead Actor < /th >
< th > Movie Type < /th >
< /tr >

c04.indd 108c04.indd 108 12/10/08 5:45:17 PM12/10/08 5:45:17 PM
Chapter 4: Using Tables to Display Data
109
< ?php
// loop through the results
while ($row = mysql_fetch_assoc($result)) {
extract($row);
echo ‘ < tr > ’;
echo ‘ < td > ’ . $movie_name . ‘ < /td > ’;
echo ‘ < td > ’ . $movie_year . ‘ < /td > ’;
echo ‘ < td > ’ . $movie_director . ‘ < /td > ’;
echo ‘ < td > ’ . $movie_leadactor . ‘ < /td > ’;
echo ‘ < td > ’ . $movie_type . ‘ < /td > ’;
echo ‘ < /tr > ’;
}
? >
< /table >
< p > < ?php echo $num_movies; ? > Movies < /p >
< /div >

7. Open the page in your web browser; it should look like Figure 4 - 2 .
Figure 4-2
c04.indd 109c04.indd 109 12/10/08 5:45:17 PM12/10/08 5:45:17 PM
Part I: Movie Review Web Site
110
How It Works
The preceding code does quite a lot of work for you, so let ’ s look at it in more detail.
First a connection to the database is established, and then you select the movies database. Next, you
issue a query to the database to retrieve the name, release year, and lead actor of some movies. The


mysql_num_rows() function takes the result reference and returns the number of total matching
records MySQL found.
The
while statement loops through the records that have been returned. It executes the block of code
that is between the braces for each record. Don ’ t worry; PHP is smart enough to know how many
records there are and what record number it is currently on, in this case, so there is no danger of
having the wrong values assigned to a record.
The first line in the
while loop uses the extract() function to create variables with the same name
as the field names and populates them with their values from the current record. The next seven lines
then simply output the values with a little HTML mixed in for good measure.

Wait a Minute
So far we ’ ve used echo to output content from within PHP mode (between the < ?php and ? > tags).
Larger chunks of HTML code are outside the tags and are output to the browser immediately, without
being parsed by PHP. The script drops in and out of PHP mode, bouncing back and forth between
HTML and PHP code. Some will argue this is the optimal way of doing things, while others will argue
it ’ s confusing and makes things more difficult to maintain. So, let ’ s take another look at
heredoc syntax.
Try It Out Putting It All Together
Copy the table1.php file to table2.php , and follow these steps.
1. Replace the HTML code responsible for the table ’ s column headers with a heredoc statement
saved to a
$table variable:
$table = < < < ENDHTML
< div style=”text-align: center;” >
< h2 > Movie Review Database < /h2 >
< table border=”1” cellpadding=”2” cellspacing=”2”
style=”width: 70%; margin-left: auto; margin-right: auto;” >
< tr >

< th > Movie Title < /th >
< th > Year of Release < /th >
< th > Movie Director < /th >
< th > Movie Lead Actor < /th >
< th > Movie Type < /th >
< /tr >
ENDHTML;
c04.indd 110c04.indd 110 12/10/08 5:45:17 PM12/10/08 5:45:17 PM
Chapter 4: Using Tables to Display Data
111
2. Replace the echo statements within the while loop with a heredoc statement, appending it to
the
$table variable:
$table .= < < < ENDHTML
< tr >
< td > $movie_name < /td >
< td > $movie_year < /td >
< td > $movie_director < /td >
< td > $movie_leadactor < /td >
< td > $movie_type < /td >
< /tr >
ENDHTML;
Note the use of .= instead of just the = sign. This is important because it appends the heredoc block to
the existing content already stored in
$table . If you just used =, the content would be replaced, which
is not what you want to happen.
3. Replace the HTML code for the closing of the table and echo statement that outputs the
number of movies returned with a
heredoc statement appended to $table .
$table .= < < < ENDHTML

< /table >
< p > $num_movies Movies < /p >
< /div >
ENDHTML;
Here is what the code in table2.php should look like now:
< ?php
//connect to MySQL
$db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or
die (‘Unable to connect. Check your connection parameters.’);

// make sure you’re using the right database
mysql_select_db(‘moviesite’, $db) or die(mysql_error($db));

// retrieve information
$query = ‘SELECT
movie_name, movie_year, movie_director, movie_leadactor,
movie_type
FROM
movie
ORDER BY
movie_name ASC,
movie_year DESC’;
$result = mysql_query($query, $db) or die(mysql_error($db));

// determine number of rows in returned result
$num_movies = mysql_num_rows($result);

c04.indd 111c04.indd 111 12/10/08 5:45:17 PM12/10/08 5:45:17 PM
Part I: Movie Review Web Site
112

$table = < < < ENDHTML
< div style=”text-align: center;” >
< h2 > Movie Review Database < /h2 >
< table border=”1” cellpadding=”2” cellspacing=”2”
style=”width: 70%; margin-left: auto; margin-right: auto;” >
< tr >
< th > Movie Title < /th >
< th > Year of Release < /th >
< th > Movie Director < /th >
< th > Movie Lead Actor < /th >
< th > Movie Type < /th >
< /tr >
ENDHTML;

// loop through the results
while ($row = mysql_fetch_assoc($result)) {
extract($row);
$table .= < < < ENDHTML
< tr >
< td > $movie_name < /td >
< td > $movie_year < /td >
< td
> $movie_director < /td >
< td > $movie_leadactor < /td >
< td > $movie_type < /td >
< /tr >
ENDHTML;
}



$table .= < <
< ENDHTML
< /table >
< p > $num_movies Movies < /p >
< /div >
ENDHTML;
? >

4. Save table2.php , and open it in your web browser. You ’ ll notice there ’ s no output! That ’ s
because you haven ’ t instructed PHP to echo back the contents of
$table .
5. Add an echo statement at the end of the file. Save and view the page again. It should now
look the same as before, as in Figure 4 - 2 .

echo $table;
How It Works
At first there was no output when you viewed the page in your web browser, because the information
was collected in the
$table variable and not sent out to the browser. The echo statement you added
at the end of the code then output it. Voil à ! The table is now visible on the page!
As you keep adding text to
$table , you need to make sure you use .= instead of just = when
assigning it. The
.= appends content after whatever is already stored in the variable, whereas = would
just replace the existing value.
c04.indd 112c04.indd 112 12/10/08 5:45:17 PM12/10/08 5:45:17 PM
Chapter 4: Using Tables to Display Data
113
As you may recall from our earlier discussion regarding using heredoc, in Chapter 2 , you can change


ENDHTML to whatever you ’ d like, but the beginning and ending tags must match. For example, this
will work fine:

$table = < < < HAHAHA
// code here
HAHAHA;

But, this will not work:
$table = < < < HAHAHA
// code here
BOOHOO;

You will receive an error such as the one shown in Figure 4 - 3 .
Figure 4-3
Note that there must be no spaces after the
< < < ENDHTML and the ENDHTML; flags. In addition, there can
be no leading space, indentation, or any other characters on the
heredoc closing tag line (semicolons
are permissible). You ’ ll receive an error if there is even one space. (You can potentially spend hours
trying to fix an error as a result of having a single space after these tags!) Always remember to delete
all spaces after these tags.
c04.indd 113c04.indd 113 12/10/08 5:45:18 PM12/10/08 5:45:18 PM
Part I: Movie Review Web Site
114
Also, heredoc syntax can be used in other places, instead of just with echo or print . It is used to
assign large blocks of content to a variable, so it could also be used to assign a SQL query statement to
a variable. For example:

$query = < < < ENDSQL
SELECT

movie_name, movie_year, movie_director, movie_leadactor
movie_type
FROM
movie
ORDER BY
movie_name ASC,
movie_year DESC
ENDSQL;

The table may look pretty, but, as in Chapter 3 , it doesn ’ t do users much good if they don ’ t have their
secret decoder ring to decipher which actors and directors were associated with your movies. You
need to link your tables to pull in this information.

Try It Out Improving Your Table
In this exercise, you ’ ll link the tables together so you can output meaningful data.
1. Modify your table2.php file as shown in the highlighted text:
< ?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
c04.indd 114c04.indd 114 12/10/08 5:45:18 PM12/10/08 5:45:18 PM
Chapter 4: Using Tables to Display Data
115
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);

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;
}
//connect to MySQL
$db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or
die (‘Unable to connect. Check your connection parameters.’);

// make sure you’re using the right database
mysql_select_db(‘moviesite’, $db) or die(mysql_error($db));

// retrieve information
$query = ‘SELECT
movie_name, movie_year, movie_director, movie_leadactor,
movie_type
FROM
movie

ORDER BY
movie_name ASC,
movie_year DESC’;
$result = mysql_query($query, $db) or die(mysql_error($db));

// determine number of rows in returned result
$num_movies = mysql_num_rows($result);

$table = < < < ENDHTML
c04.indd 115c04.indd 115 12/10/08 5:45:18 PM12/10/08 5:45:18 PM

×