Using mysqli_fetch_assoc in PHP to Retrieve Rows as Associative Arrays
This article explains how to connect to a MySQL database with PHP, execute a SELECT query, and use the mysqli_fetch_assoc function to fetch rows as associative arrays, including code examples and best‑practice notes for handling multiple rows.
In PHP, interacting with a database is a common task. When we execute a SELECT query and obtain a result set, we usually need to store the data in a PHP array for further processing.
PHP provides several functions for handling result sets, and one frequently used function is mysqli_fetch_assoc . This function retrieves one row from the result set as an associative array, making it easy to access data by column name.
Below is a complete example that demonstrates how to use mysqli_fetch_assoc to fetch a row from a result set:
<?php
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
exit();
}
// Execute SELECT query
$result = $mysqli->query("SELECT * FROM users");
// Verify that rows were returned
if ($result->num_rows > 0) {
// Fetch one row as an associative array
$row = mysqli_fetch_assoc($result);
// Output the values
echo "ID: " . $row['id'] . "
";
echo "Name: " . $row['name'] . "
";
echo "Age: " . $row['age'] . "
";
} else {
echo "No data found.";
}
// Close the connection
$mysqli->close();
?>In the example, the query result is stored in $result . The call mysqli_fetch_assoc($result) returns a single row, which we store in $row . The $row array can then be accessed by field names such as 'id' , 'name' , and 'age' .
It is important to note that each call to mysqli_fetch_assoc returns the next row in the result set; when no more rows are available, it returns null . Therefore, to retrieve multiple rows you would typically place the call inside a loop.
Using mysqli_fetch_assoc simplifies handling database query results, improves code readability, and enhances maintainability.
In summary, the provided example shows how to use the PHP function mysqli_fetch_assoc to fetch a row from a result set as an associative array, which can be very helpful during development.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.