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:
1 2 3 |
Create database blog; |
Create Table:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
CREATE TABLE `blog` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `title` VARCHAR(255) NULL DEFAULT NULL, `blog_content` TEXT NULL, `author` VARCHAR(255) NULL DEFAULT NULL, `created` DATETIME NULL DEFAULT NULL, PRIMARY KEY (`id`) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB AUTO_INCREMENT=12 ; |
Create Database Connection:
1 2 3 4 5 6 7 8 |
$conn = mysqli_connect("localhost","root","","demo"); if(!$conn) { die("Connection error: " . mysqli_connect_error()); } |
Example 1: Using mysqli_fetch_row()
1 2 3 4 5 6 7 8 9 |
$qry = "select * from blog limit 1"; $rs = mysqli_query($conn,$qry); $getRow = mysqli_fetch_row($rs); echo "<label>Title: </label>".$getRow['1']; echo "<br>"; echo "<label>Content: </label>".$getRow['2']; |
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]
Example 2: Using mysqli_fetch_assoc()
1 2 3 4 5 6 7 8 9 |
$qry = "select * from blog limit 1"; $rs = mysqli_query($conn,$qry); $getRowAssoc = mysqli_fetch_assoc($rs); echo "<label>Title: </label>".$getRowAssoc['title']; echo "<br>"; echo "<label>Content: </label>".$getRowAssoc['blog_content']; |
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: