Using mysqli_fetch_assoc to Retrieve Rows as Associative Arrays in PHP
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 tips for handling multiple rows.
Interacting with a database in PHP is a common task, and after executing a SELECT query you often need to store the result set in a PHP array for further processing.
PHP provides several functions for handling result sets, with mysqli_fetch_assoc being a frequently used one. It fetches a row from the result set as an associative array, allowing access to data by column name.
Below is a complete example demonstrating how to use mysqli_fetch_assoc to retrieve a single 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 data was returned
if ($result->num_rows > 0) {
// Fetch one row as an associative array
$row = mysqli_fetch_assoc($result);
// Output values using column names
echo "ID: " . $row['id'] . "<br>";
echo "Name: " . $row['name'] . "<br>";
echo "Age: " . $row['age'] . "<br>";
} else {
echo "No data found.";
}
// Close the connection
$mysqli->close();
?>In the example, we first create a new mysqli instance to connect to the database and check the connection. Then we run a SELECT query and store the result in the $result variable. Using mysqli_fetch_assoc, we fetch one row into $row and access its fields by name.
Note that each call to mysqli_fetch_assoc returns the next row in the result set, and it returns null when there are no more rows. To retrieve multiple rows, you can place the call inside a loop that continues until mysqli_fetch_assoc returns null.
Using mysqli_fetch_assoc simplifies extracting data from query results as associative arrays, improves code readability, and enhances maintainability when working with database queries in PHP.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
