Using mysqli_fetch_assoc to Retrieve Query Results in PHP
This article demonstrates how to connect to a MySQL database using mysqli, execute SELECT queries, and retrieve results row by row with the mysqli_fetch_assoc function in PHP, providing complete code examples for connection, querying, result iteration, and proper resource cleanup.
In PHP, database operations are essential, and the mysqli extension is commonly used. This article explains how to use the mysqli_fetch_assoc function to fetch query results.
1. Connect to the Database
First, use mysqli_connect to establish a connection to a MySQL database. Example code:
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 检查连接是否成功
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}2. Query the Database
Next, execute a SELECT statement with mysqli_query . Example:
$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);After the query, iterate over the result set using mysqli_fetch_assoc , which returns each row as an associative array until no rows remain.
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . ", Name: " . $row["name"] . ", Email: " . $row["email"] . "
";
}3. Full Example
The following complete script combines connection, query, and result processing with mysqli_fetch_assoc :
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 检查连接是否成功
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . ", Name: " . $row["name"] . ", Email: " . $row["email"] . "
";
}
} else {
echo "0 结果";
}
mysqli_close($conn);Note that the database credentials and table structure should be adjusted to match your environment.
Conclusion
The article demonstrates how to retrieve query results in PHP by connecting to the database, executing a SELECT query, and looping through the result set with mysqli_fetch_assoc , simplifying data handling and improving development efficiency.
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.