In the previous lesson, we learnt how to send data to the database. Now it’s time to retrieve data from our database to our PHP pages.
This is really one of the most important lessons in this book. Once you have read and understood this lesson, you will realize why database-driven web applications are so robust.
To retrieve data from a database, you use select queries like –
SELECT * FROM employees
Data display from database to the web page will process in two steps –
– The very first it will count the number of rows. You should know the number of the records in your table.
– Secondly we have to set the loop accordingly. Each time it will be incremented by one. It will fetch each row of the result and print the data stored there.
There are some popular methods to retrieve records from the database in PHP-
mysql_fetch_row(): It will fetch result row as an numeric way. it returns a row where the values will come in the same order as they are defined in the SQL query.
mysql_fetch_assoc():It will fetch a result row as an associative array. This function will return a row as an associative array where the column names will be the keys storing corresponding value. Means we can fetch our record through the table column name.
mysql_fetch_array(): It will fetch a result row as an associative array or a numeric array. So this is the combination of both the method of mysql_fetch_row and mysql_fetch_assoc.
mysql_fetch_object(): It will fetch a result row as an object
Example 1: To retrieve data from Mysql Table- Lets retireve records of recently added table as below-
Database Name: mydb
Table Name: employees
Column List: name, email, password, phone
// Prepare a database connectivity first
$con = mysqli_connect(“localhost”, “root”, ” “, “mydb”);
// Prepare SQL Statements to fetch record
$query = mysqli_query(“SELECT * from employees”;
// Use any fetch method to retrieve records
while ($row = mysqli_fetch_assoc($query))
/* Now you can display columns using $row variable as all records to be proceed by the $row variable */
echo $row[‘name’]. “<br>”;
echo $row[‘email’]. “<br>”;
/* close connection */