Displaying MySQL Data

Warning: This article/tutorial is more the 45 days old. As such the information contained within could be, by now, out of date. Please read all information to make sure that this article/tutorial will work with your current version of the Operating System

In this tutorial, we will learn how to retrieve and display data from a MySQL database using PHP. This tutorial is a perfect companion to my tutorial entitled “Writing Form Data to a MySQL Database using PHP” so we will use the same database information – a table named “colors”, fields named “name” and “favoriteColor” with the following connection data:
Host: localhost
Username: lefteh
Password: 1234
DB Name: MyDB
Remember, these pieces of data are just examples. Remember to replace them with your own data.

Okay, first we’ll create a skeleton.



Displaying MySQL Data


Our PHP code will go in the body of the document.

First, we’ll connect to the database. In this step, we will also create the beginning and end of a table, because that is what our results will be printed into.



Displaying MySQL Data



With me so far?

We set our four connection variables, connected to the MySQL server, and selected the database. Then, we created the beginning and end tags of a table.

Printing our data is actually quite easy. It is a simple while loop. In the argument of the loop, we set a variable to mysql_fetch_array($query). Then, whatever is inside the brackets is repeated for every row in the table. Furthermore, we can use the variable that we used in the argument as an array using the column names of our database. Now, for the query, we will want to select all columns from “colors”. Therefore, our query is “SELECT * FROM colors”. Confused? Me too. Just look at the example:



Displaying MySQL Data


“;
echo “

“;
echo “

“;
echo “

“;
}
?>

“.$row[‘name’].” “.$row[‘favoriteColor’].”


Understand? All we do is put a table row on a loop, with two table cells each displaying a different MySQL field. Now, keep in mind displaying MySQL data can be manipulated much more. We don’t have to put it in a table, you can just make a loop that echos the variables. You can use the $row[‘fieldname’] for all fields in the database.

Displaying MySQL can be extremely confusing for some, so feel free to drop me a line.

Leave a Reply

Your email address will not be published. Required fields are marked *