By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Selecting or Outputting from the MySQL Table

Tutorial on how to output data from an MySQL table with PHP

Edited: 2015-07-10 16:41

The final step is how you are going to output Data from your table, and this is actually easier then inserting.

Before we start, lets consider which fields we need. We likely need both the Name, Text and Time fields, since this is a Guestbook. We didn't make a name field in our table, nor a field for emails.

This will be your task in the next Tutorial.

The MySQL Select

In our case the select would look something like below.

SELECT * FROM GuestBook_Posts ORDER BY PostID;

The above query would just make MySQL select everything in the table, and that would be fine in this simple case. But in cases where you would have more fields, such as Email, website etc. We would instead do something like below.

SELECT PostID, Text, Time, Website FROM GuestBook_Posts ORDER BY PostID;

The reason for this is Performance. Its slower to select all fields in a table, then it is to only select the fields we need.

But lets stick to this case for now. The PHP for the first Example is.

<?php

$SelectedRows = mysql_query("SELECT * FROM GuestBook_Posts ORDER BY PostID", $Connection);

?>

Note the extra variable, this will contain the response, we will fetch the response in an Array, and output it with a While Loop.

while ($SelectedRows = mysql_fetch_array($SelectedRows, MYSQL_ASSOC)) {

echo "<p>" . $SelectedRows['Text'] . "</p>";

}

Try to experiment, and output other rows, the above would output the Text field of all Rows in the Table.

Full Example

The full PHP code is

<?php

$SelectedRows = mysql_query("SELECT * FROM GuestBook_Posts ORDER BY PostID", $Connection);

while ($SelectedRows = mysql_fetch_array($SelectedRows, MYSQL_ASSOC)) {

echo "<p>" . $SelectedRows['Text'] . "</p>";

}

?>