How to fetch single row from Database in PHP

When I was a PHP beginner I know how difficult was to communicate with database. First I had to create database connection and then type query and then run that query to get the desire result.

I know some of you are facing exactly same problem in dealing with database. But don’t worry in this post I am going to show you how to fetch single from database in php.

Fetch single row from database in PHP

This tutorial is for beginner so i will use simple mysqli function to get data from database. Php also provide mysqli class and PDO to insert and fetch data from mysql database.

In this post I will show you 2 examples to get data. In first example I will use mysqli_fetch_row() and in second example will use mysqli_fetch_assoc(). mysqli_fetch_assoc() is also used in fetching multiple records.

Create Database:

Create Table:

Create Database Connection:

Example 1: Using mysqli_fetch_row()

In the above code $qry has simple mysql query which get only 1 record from database. $rs variable holds mysqli_query function which takes 2 arguments. First argument is database connection string and second argument is sql statement. Then I used mysqli_fetch_row() function and passed $rs into it and store fetch record(array) into $getRow variable. Next I just simply print title and content by calling $getRow[1] and $getRow[2]

Note: mysqli_fetch_row() returns record array with numeric indexes

Example 2: Using mysqli_fetch_assoc()

In the above code first 2 lines are similar to example 1 but in 3rd line $getRowAssoc get single record from database with column names as array indexes. Then I print title and content in next lines using $getRowAssoc['title'] and $getRowAssoc['blog_content'].

Also read:


Posted in PHP

Author: Ahsan Zameer

I am a web developer and love to search new stuff on web. Trying different approaches and ideas to make web developing more interesting and enjoyable.

Leave a Reply

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