Using mysqli_fetch_assoc to Retrieve Rows as Associative Arrays in PHP
This article explains how to connect to a MySQL database in PHP, execute a SELECT query, and use the mysqli_fetch_assoc function to fetch rows as associative arrays, including sample code and notes on handling multiple rows and error checking.
In PHP, interacting with a database is a common task; when we run 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 a frequently used one is mysqli_fetch_assoc , which retrieves a row from the result set as an associative array, allowing access to data by column name.
The following example demonstrates how to use mysqli_fetch_assoc to fetch a row from a result set:
connect_errno) {
echo "连接数据库失败:" . $mysqli->connect_error;
exit();
}
// Execute SELECT query
$result = $mysqli->query("SELECT * FROM users");
// Check if data returned
if ($result->num_rows > 0) {
// Fetch one row as associative array
$row = mysqli_fetch_assoc($result);
// Output values
echo "ID: " . $row['id'] . "
";
echo "姓名: " . $row['name'] . "
";
echo "年龄: " . $row['age'] . "
";
} else {
echo "没有查询到数据。";
}
// Close connection
$mysqli->close();
?>In the example, we first connect to the database using new mysqli and check the connection. Then we execute a SELECT query, storing the result in $result . We then call mysqli_fetch_assoc to fetch a row into $row and output its fields by name.
Note that mysqli_fetch_assoc returns the next row each time it is called and returns null when no more rows are available; to fetch multiple rows, call it repeatedly inside a loop.
Using mysqli_fetch_assoc makes it convenient to retrieve rows as associative arrays, improving code readability and maintainability when processing query results.
php8, I'm here
Scan the QR code to receive free learning materials
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.