fetch_assoc
In this article, we will focus on the mysqli_fetch_assoc() function in PHP, which is used to fetch a row from a MySQLi result set as an associative array. We
In this article, we will focus on the mysqli_fetch_assoc() function in PHP, which is used to fetch a row from a MySQLi result set as an associative array. We will provide you with an overview of the function, how it works, and examples of its use.
Introduction to the mysqli_fetch_assoc() function
This built-in PHP function retrieves a row from a MySQLi result set and returns it as an associative array. It is useful when you need to access query results by column name rather than numeric index.
How to use the mysqli_fetch_assoc() function
Using the mysqli_fetch_assoc() function is straightforward. You call it on a valid MySQLi result set, typically inside a while loop to process multiple rows. Here is an example:
How to use the mysqli_fetch_assoc() function?
<?php
$mysqli = mysqli_connect("localhost", "username", "password", "database");
if (!$mysqli) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM my_table WHERE id = 1";
$result = mysqli_query($mysqli, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['column1'] . " - " . $row['column2'];
}
} else {
echo "Query failed: " . mysqli_error($mysqli);
}
mysqli_close($mysqli);
?>In this example, we first check the connection status and handle potential errors. We then execute a query using the mysqli_query() function and verify the result. Instead of checking $result alone, we use a while loop with mysqli_fetch_assoc() to safely iterate through each row. The function returns null when no more rows are available, automatically ending the loop. Finally, we close the database connection.
Conclusion
The mysqli_fetch_assoc() function is a reliable way to fetch rows from a MySQLi result set as associative arrays. By integrating it into a while loop and adding basic error handling, you can safely and efficiently process query results in your PHP applications.
Practice
What does the fetch_assoc() function in PHP do?