Lab 8: PHP and MySQL Together
There is a lot to learn about the interaction between PHP and MySQL that
facilitates hundreds of data-driven web sites, including Facebook. But the
basic tools can be covered relatively quickly. In today’s lab we will
carefully explore the most important features of PHP that allow programs
to interact with MySQL databases.
Complete the following activities involving writing database-driven web applications in
PHP (and also some further experience with PHP itself).
DESIGN ALL SOLUTIONS BEFORE CODING.
Note that copies of the code we have worked on in class have been uploaded to Box.
Everything you’re being asked to do today is directly analogous to examples you’ve seen
in lecture. But don’t rely on simply copying this code. Unless you thoroughly understand
what it is doing, you won’t be successful in the following activities.
1. Copy the lab8 folder from Box to your CSC105 Labs folder on your USB
drive. Use Dreamweaver to open the files contained in the folder and carefully
read the comments that I have provided (preceded by the symbols //). You don’t
have to upload anything to the server yet. Just take some time to absorb the code.
Connecting to a MySQL Database
PHP provides a rich collection of built-in functions for database access. You basically
just have to remember a few simple lines of code to accomplish specific tasks. To
connect to a MySQL database, use the functions mysql_connect and
mysql_select_db, as in the following example:
$linkID = mysql_connect("localhost","userID","userpass");
mysql_select_db("databaseName", $linkID);
The first line is used to log into your MySQL account on the server. Your connection
information is assigned to a PHP variable (called “$linkID” in this example). The next
line makes the connection to a specific database in your account. (Remember from
lecture that you can have several such connections in one program.)
2. Modify the listAllCustomers.php file so it uses your own userID,
password, and database name. (The word “localhost” should remain unchanged.)
Then upload your lab8 folder to your www directory on the server and test it:
(http://cs.furman.edu/~yourlogin/lab8/listAllCustomers.php). You
should be able to predict the results based on what you’ve seen in class (except
that I have removed all of the table formatting).
3. Create a file called allProducts.php in your lab8 folder. (If you like, you
can do this by saving a copy of listAllCustomers.php, as long as you
promise to understand this code and not just copy it.) Enter (or modify) the PHP
CSC-105: Introduction to Computer Science
page 2
code necessary to connect to MySQL and select your database. Again, be sure to
use your own userID, password, and database name. You don’t have to upload or
test this new file yet. Ask me or the lab assistant if you’re not sure about anything
we’ve covered up to this point.
Getting Information Out of the Database
This is where you put your knowledge of SQL to use. Once you have an active
connection to your database, you can basically do anything you like with it. The key is
understanding SQL commands. Recall that searching the database for information
involves the SELECT command. Doing so in a PHP program also involves the special
PHP functions mysql_query and mysql_fetch_assoc. Here’s how it works:
$SQL = “SELECT name,phone FROM Customers ORDER BY name”;
$allValues = mysql_query($SQL, $linkID);
First, we create the SQL query that we want to run and assign it to a variable (called
$SQL in this case, but you can name it anything you want). The function
mysql_query selects the requested records/rows from the database and stores all of
them in another variable ($allValues in this example, though again you can pick your
own variable name).
It is good PHP programming practice to check to make sure a query was successful. This
can be done with the following code:
if (!$allValues) {
echo “Could not execute query ($SQL): “ . mysql_error();
exit;
}
If the query was unsuccessful, the variable $allValues will contain the value FALSE.
In that case, this code will print (1) an error message, (2) the original query, and (3) an
explanation of the error in the event of a failed query. It will then terminate the
application. This code is enormously useful when you are debugging your program.
4. Open your MySQL account (http://cs.furman.edu/phpMyAdmin/) and
write and test a query to display all the product descriptions and unit prices from
the Products table, in alphabetical order of product description. Make sure
your query is correct before continuing.
5. In your allProducts.php file, enter (or modify) the PHP code necessary to
run your new query, analogous to the example above (and to the code that was
provided to you). This time, you may choose to upload the file and test it. A
successful test will display a blank page because we haven’t finished coding yet.
An unsuccessful test will display an error message, because something is wrong
with your query.
CSC-105: Introduction to Computer Science
page 3
Displaying the Information from the Database
If the query is successful, the next step is to get the data out of the variable, one row at a
time, so it can be displayed. Consider the following lines of code:
$thisValue = mysql_fetch_assoc($allValues);
extract($thisValue);
The PHP function mysql_fetch_assoc() grabs a single row of data from the
$allValues variable and stores it in $thisValue. (As always, these variable names
are arbitrary. You can make up your own.) The PHP extract() function pulls all the
data out of that row and stores it in variables named – very conveniently – after the names
of the fields in your database. Now you can access the data from the record just by using
the original field names. For instance, if your query involved fields called “name” and
“phone” (as in the previous example), you could display them like this:
echo $name;
echo $phone;
The nice thing about the function mysql_fetch_assoc() is that it automatically
moves to the next record every time you call it. This is useful for looping through data.
For instance:
$SQL = “SELECT name,phone FROM Customers ORDER BY name”;
$allValues = mysql_query($SQL, $linkID);
if (!$allValues) {
echo “Could not execute query ($SQL): “ . mysql_error();
exit;
}
$totalrows = mysql_num_rows($allValues);
for ($i=1; $i <= $totalrows; $i++)
{
$thisValue = mysql_fetch_assoc($allValues);
extract($thisValue);
echo “$name, ”;
echo “$phone”;
echo “<BR>”;
}
After you’ve worked with your database, you must be sure to close the connection that
you’ve made. This line of code will do that, at the very end of your program:
mysql_close($linkID);
6. Update your allProducts.php file to display the results of your Products
table query with product descriptions and unit prices, one line per product. Use
the preceding Customer example and the provided code as a guide. (But
remember – it’s just an example! Copying and pasting the exact same code won’t
work!)
CSC-105: Introduction to Computer Science
page 4
7. When you have all of the data displaying on your page, save the program to a new
file called allProducts2.php and modify the program to display the data in a
different format using dashes and a dollar sign:
Ace blue bike -- $95.45
Ace red bike -- $89.59
…
and so on. Feel free to be creative on this step. Future programming assignments
will require your formatting creativity.
8. Create a new file called orderQuery.php. Using the solution to the previous
problem as a guide, write a new program that displays the customer names, phone
numbers, and product numbers for all orders placed in July. You may choose how
to format the data. Either way, format the data nicely – don’t just let it run
together. (NOTE: This problem requires very little change in your code!
Practically the whole problem is writing the correct SQL statement.)
HINT: Write and test the query directly in phpMyAdmin first, so you’ll know it’s
correct before you try it in a PHP program. This is always good advice.
9. For your final activity today, write a form called productSearch.html that
allows a user to search for a particular product in your DB based on a product
number entered by the user. When a “Search” button is clicked, a second page
(call it searchResults.php) should display the description and unit cost of
any product with a matching product number. If no products match the search,
display a “not found” message and give the user a chance to try again. Make the
interface as user-friendly as possible. Display/format the data nicely.
HINT: Once again, go back to the lecture examples for a model of how to do this.
The code from lecture is in Box so you don’t have to type it from scratch. But
remember that the example isn’t identical to this problem! You can’t just copy and
paste the code. If you understand the class example, you should have a pretty good
idea for how to do this one. What you want to be working towards is that
understanding, more than just getting this program to work.
10. If you’ve named all the files for this lab correctly, the index page that I provided
for you should link to each of your solutions. That is, when you’re done with this
lab, you should be able to pull up all of your solutions easily by accessing
http://cs.furman.edu/~yourlogin/lab8/ Before you finish, go to
this page and make sure that all of your links work.
Be sure to get a copy of the assignment for Program #4 before you leave.
FINAL NOTE: If you would like to experiment with the use of HTML tables to
format your results from this lab – as demonstrated in the lecture examples – I will
consider such experimentation for extra credit. Sample code for building HTML
tables can be found in the lecture notes and in the code examples on Box.