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.
| Function | Returns 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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |