The mysqli_fetch_assoc()
function in PHP is used to fetch a result row as an associative array from a result set obtained using a MySQLi query.
🔹 Syntax:
mysqli_fetch_assoc(mysqli_result $result): array|null
- $result: The result object from a
mysqli_query()
call. - Returns: An associative array of strings representing the fetched row, where column names are the keys, or
NULL
if there are no more rows.
🔹 Key Features:
- Only returns associative arrays (i.e., no numeric keys).
- Used commonly in
while
loops to fetch multiple rows.
🔹 Example 1: Basic usage
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . "<br>";
echo "Name: " . $row["name"] . "<br>";
echo "Email: " . $row["email"] . "<br><br>";
}
mysqli_close($conn);
?>
Output (example):
ID: 1
Name: John
Email: john@example.com
ID: 2
Name: Alice
Email: alice@example.com
🔹 Example 2: Using fetched data in an array
<?php
$users = [];
$result = mysqli_query($conn, "SELECT * FROM users");
while ($row = mysqli_fetch_assoc($result)) {
$users[] = $row; // Store each row in $users array
}
print_r($users);
?>
Output (structure):
Array (
[0] => Array ( [id] => 1 [name] => John [email] => john@example.com )
[1] => Array ( [id] => 2 [name] => Alice [email] => alice@example.com )
)
✅ When to Use mysqli_fetch_assoc()
:
- When you only need column names as keys, without numeric indexes.
- In
while
loops to iterate through rows. - When building APIs or JSON responses.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.