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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php $host = "localhost"; $user = "root"; $pass = ""; $db = "demo"; $conn = mysqli_connect($host,$user,$pass, $db); if(!$conn) { die("Connection failed: " . mysqli_connect_error()); } ?> |
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.
1 2 3 4 5 6 |
<?php $sql = "select * from posts"; $result = mysqli_query($conn,$sql); ?> |
Step 3: Fetch Single row
mysqli_fetch_row()
function is used to fetch row against sql statement.
1 2 3 4 |
$singleRow = mysqli_fetch_row($result); print_r($singleRow); |
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
.
1 2 3 4 5 6 7 |
while($row = mysqli_fetch_assoc($result)) { print_r($row); } |
Step 5: All together
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php $host = "localhost"; $user = "root"; $pass = ""; $db = "demo"; $conn = mysqli_connect($host,$user,$pass, $db); if(!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "select * from posts"; $result = mysqli_query($conn,$sql); //for single row $singleRow = mysqli_fetch_row($result); print_r($singleRow); echo "<hr>"; //for all records while($row = mysqli_fetch_assoc($result)) { print_r($row); } ?> |