In how many ways can we fetch data from a MySQL result set in PHP?

With the MySQLi extension there are five main functions to read rows from a result set.

FunctionReturns the row as
mysqli_fetch_assoc()Associative array (keys are column names)
mysqli_fetch_row()Numeric array (keys are 0, 1, 2…)
mysqli_fetch_array()Both associative and numeric array
mysqli_fetch_object()Object (columns are properties)
mysqli_fetch_all()All rows together in one array

This example uses the users table from our MySQL chapters. Suppose the user with id 1 is “Ram”.

<?php
require_once('db-connection.php');

$sql = "SELECT id, name FROM users WHERE id = 1";

$row = mysqli_fetch_assoc(mysqli_query($conn, $sql));
echo $row["name"] . "<br>";

$row = mysqli_fetch_row(mysqli_query($conn, $sql));
echo $row[1] . "<br>";

$row = mysqli_fetch_object(mysqli_query($conn, $sql));
echo $row->name;
?>

Output:

Tutorials Class - Output Window

Ram
Ram
Ram

Note: The old mysql_fetch_* functions (without the “i”) were removed in PHP 7. Always use mysqli or PDO. See PHP mysqli_query().

fetch_assoc() is the most used, because the code is easy to read. Use fetch_all() only when the result is small, as it loads every row in memory.


Learn more about the similar topics:
Tutorials
PHP MySQL Tutorial
PHP : MySQL Database
PHP : MySQL Connect
PHP : MySQL Create Database
PHP : MySQL Create Table
PHP : MySQL INSERT Statement
PHP : MySQL Select Data
Exercises & Assignments
Display MySQL data in an HTML table using mysqli_fetch_array()
Interview Questions & Answers
What is the difference between mysqli_fetch_array() and mysqli_fetch_object()?
How to Fix Incorrect format parameter error when importing large database in PHPMyAdmin?
In how many ways can we fetch data from a MySQL result set in PHP?
How to encrypt and decrypt data stored in a MySQL table?
What is the difference between mysqli and PDO in PHP?