How to fetch data from Mysql using PHP

In this tutorial I am going to show you how to fetch data from mysql using php. Let’s take an example of my last post that was insert data in mysql using php form. In that post I have created a form with 2 fields and save both of fields in a mysql table with datetime. In this post we are going to fetch data from posts table.

Step 1: Create database connection:

We have already created database as demo in my previous post so no need to create new database. Only mysql database connection is required.

Step 2: Write and run mysql fetch query

$sql variable is a sql statement. $result is calling mysqli_query() function which takes 2 parameter, 1 is a database connection and 2 is a sql statement.

Step 3: Fetch Single row

mysqli_fetch_row() function is used to fetch row against sql statement.

If you want fetch all records against $sql query then you need to apply while loop.


Step 4: Fetch all data from mysql

mysqli_fetch_array and mysqli_fetch_assoc both function are used to fetch data from mysql . Only difference is mysqli_fetch_assoc returns column name with data and mysqli_fetch_array returns numeric key. I personally use mysqli_fetch_assoc.

Step 5: All together

 

Posted in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *