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.. Try It Out Using
Trang 1Quer ying 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:
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 customersSELECT * FROM customers;
Trang 2Let ’ 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.’);
Trang 3movie_year > 1990 ORDER BY
movie_type’;
$result = mysql_query($query, $db) or die(mysql_error($db));
// show the resultswhile ($row = mysql_fetch_array($result)) { extract($row);
echo $movie_name ‘ - ‘ $movie_type ‘ < br/ >
Trang 4You 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 * 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
Trang 5Try 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:
$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 resultswhile ($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
Trang 6Try 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.’);
// show the results
echo ‘ < table border=”1” >
while ($row = mysql_fetch_assoc($result)) {
Trang 7Figure 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
❑
❑
Trang 8Referencing 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
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
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.’);
Trang 9movie.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 resultsecho ‘ < 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
Trang 10How 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.’);
// show the results
echo ‘ < table border=”1” >
Trang 11while ($row = mysql_fetch_assoc($result)) { echo ‘ < tr >
foreach ($row as $value) { echo ‘ < td > ’ $value ‘ < /td >
} echo ‘ < /tr >
}echo ‘ < /table >
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?
Trang 12Helpful T ips 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
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
Trang 13In 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, Figure 3-4
Trang 154
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