What is the difference between mysqli_fetch_array() and mysqli_fetch_object()?
Both functions read one row from a MySQL result, but the format of the row is different.
| Function | Returns the row as | How to read a value |
|---|---|---|
| mysqli_fetch_array() | An array with both numeric and column-name keys | $row["name"] or $row[0] |
| mysqli_fetch_object() | An object, columns are properties | $obj->name |
| mysqli_fetch_assoc() | An array with column-name keys only | $row["name"] |
The examples use the users table of our MySQL chapters. Suppose the user with id 1 is Ram.
<?php
require_once('db-connection.php');
$sql = "SELECT name, email FROM users WHERE id = 1";
$row = mysqli_fetch_array(mysqli_query($conn, $sql));
echo $row["name"] . " / " . $row[1] . "<br>";
$obj = mysqli_fetch_object(mysqli_query($conn, $sql));
echo $obj->name . " / " . $obj->email;
?>
Output:
Tutorials Class - Output Window
Ram / ram@example.com
Ram / ram@example.com
In the first line, $row[1] is the second column (email), because the numeric keys start from 0. Most developers prefer mysqli_fetch_assoc(), because it does not keep every value two times. See all the options in ways to fetch data from a result set.
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() |