PHP MySQL tutorial - Retrieving data from the database


Home - Tutorials - Databases

In this PHP MySQL tutorial I will show you how to use basic database manipulation features in PHP.

Tutorial info:


Name:PHP MySQL tutorial
Total steps:5
Category:Databases
Level:Beginner

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:

Code:
  1. mysql_connect("localhost", "username", "password") or die(mysql_error());
  2.  
  3. $result = mysql_query("SELECT * FROM users");
  4.  
  5. echo $result;
  6.  

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.

Code:
  1. $row = mysql_fetch_assoc($result);
  2.  
  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:
 
Code:
  1. $result = mysql_query("SELECT * FROM users");
  2.  
  3. while($row = mysql_fetch_assoc($result)){
  4. echo "ID: ".$row['id'].", Name:".$row['name']
  5. .", City:".$row['city'].", Age:".$row['age']."<br/>";
  6. }
  7.  

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
AJAX F1
CSS F1
Database F1
Flash F1
HTML F1
Java F1
JavaScript F1
PhotoShop F1
PHP F1
Scripts F1
Tutorial F1
Windows F1

Total time: 0.12