Viewing data from a database

A tutorial on viewing data from a database

There are many ways to retrieve data from a database this tutorial will show you a popular way of selecting the data you want and then printing it to the page.

This tutorial assumes you have a basic knowledge of PHP

To start off include your database connection details

Select what you want to display from the database to select everything use * which stands for ‘All’

If you wanted to select certain fields you can specify them like:

Then add the results to a variable called result

Then were going to get all the affected rows using the function mysql_num_rows and add it to a variable called Rows

We now create a new variable and give it a value of 0

To get all rows instead of just one we need to loop through all results until there is no more. To do this we will use a while loop.

The while loop remains true while $Rows is less then $i once false the while loop stops. Inside the while loop we add the result, $i variable and the row name to a variable of the same name.

We now have the data from the database and want to show the data on the screen so we echo the data and add some html tags to make them more readable while inside the loop.

At the end of the loop we set $i to increment (++) for each loop. Then close the loop.

You will now have the data from the database provided there is some data to show. To print a message when there is nothing to show you can use a simple if statement

If $i is equal to 0 meaning there is no data print a message.

Here’s the full code: