← Back to Chapters

PHP MySQLi Fetch Functions

? PHP MySQLi Fetch Functions

? Quick Overview

When executing SELECT queries using MySQLi in PHP, fetch functions are used to retrieve rows from the result set. Each function returns the data in a different structure such as associative arrays, numeric arrays, or objects.

? Key Concepts

  • mysqli_fetch_assoc() – Associative array
  • mysqli_fetch_row() – Numeric array
  • mysqli_fetch_object() – Object-based access
  • mysqli_fetch_array() – Both numeric and associative

? Syntax & Theory

Fetch functions work on the result object returned by mysqli_query() or $conn->query(). Each call retrieves one row and moves the internal pointer forward.

? Code Example

? View Code Example
// Connect to MySQL database using MySQLi
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, first_name, last_name, email FROM users";
$result = $conn->query($sql);

// Fetch rows as an associative array
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: ".$row["id"]." Name: ".$row["first_name"]." ".$row["last_name"]." Email: ".$row["email"]."<br>";
}
} else {
echo "0 results";
}

$conn->close();
?>

? Live Output / Explanation

The script connects to the database, runs a SELECT query, and fetches each row using mysqli_fetch_assoc(). Column values are accessed by their names.

? Interactive Concept

Try switching between different fetch functions and observe how the returned data structure changes when using arrays versus objects.

? Use Cases

  • Displaying user lists
  • Fetching records for dashboards
  • Processing query results dynamically
  • Rendering database-driven HTML tables

✅ Tips & Best Practices

  • Prefer mysqli_fetch_assoc() for readability
  • Use objects when working with OOP-based code
  • Always check num_rows before fetching
  • Close connections after use

? Try It Yourself

  • Fetch data using mysqli_fetch_row()
  • Display results using mysqli_fetch_object()
  • Create an HTML table from fetched data
  • Add pagination using LIMIT