PHP MySQL tutorial - Retrieving data from the database

Home - Tutorials - Databases


Tutorial info:

Name:PHP MySQL tutorial
Total steps:5

Bookmark PHP MySQL tutorial

Bookmark and Share

Step 3 - Retrieving data from the database

PHP MySQL tutorial

Now it's time to make something more interesting work. For example let's try to retrieve data from our table. To do this we first need to open a connection and select the relevant database as before. The next step is to send an SQL query - in this case a Select statement - to the database. Now try to get all records from MySQL. The SQL statement for this is:

SELECT * FROM users;

We need to send this command to the server and store the response. We can do this by using the mysql_query() function in this way:

  3. $result = mysql_query("SELECT * FROM users");
  5. echo $result;

Ok, this is nice but  how to display data from the $result variable. If you try to print it with echo then you will get an output something like this:


Resource id #3

This is not what we want. To display the selected data correctly you need to do a bit more. There are more functions in PHP which you can use to retrieve data from a MySQL database result set. These are the followings:

All of them converts one record of the result to an array and later you can use this array as you want. To get the array you need to call one of the above mentioned function. In this case I use the associative version.

  1. $row = mysql_fetch_assoc($result);
  3. echo "ID: ".$row['id'].", Name:".$row['name']
  4. .", City:".$row['city'].", Age:".$row['age']."<br/>";

However the function returns only with one record, but we should have 5 records in the result set. To list all of the records we need to create a loop. The fetch functions returns with an array if there is a record in the result set and returns false if no more records are available. So creating a while loop is very simple as here:
  1. $result = mysql_query("SELECT * FROM users");
  3. while($row = mysql_fetch_assoc($result)){
  6. }

As you can see it is not a complicated task. In the next section we will insert data into the database.


Previous Step of PHP MySQL tutorialNext Step of PHP MySQL tutorial

Tags: php mysql tutorial, php mysql, php database, php, mysql, tutorial

Follow phpf1 on Twitter

F1 Site Family
Database F1
Java F1
JavaScript F1

Total time: 0.0239