Backend Development 4 min read

Using mysqli_fetch_assoc to Retrieve Query Results in PHP

This tutorial demonstrates how to connect to a MySQL database in PHP using mysqli_connect, execute queries with mysqli_query, and retrieve each row as an associative array using mysqli_fetch_assoc, providing complete code examples and a full script for efficient backend data handling.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using mysqli_fetch_assoc to Retrieve Query Results in PHP

In PHP, database operations are a core part of development, and the mysqli extension is a common way to work with MySQL. This article explains how to use the mysqli_fetch_assoc function to obtain query results.

1. Connect to the Database

First, use mysqli_connect to establish a connection to a MySQL server. Below is a sample code snippet:

$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (! $conn) {
    die("连接失败: " . mysqli_connect_error());
}

2. Query the Database

Next, execute an SQL statement with mysqli_query . Example:

$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);

After running the query, fetch each row using mysqli_fetch_assoc , which returns the row as an associative array. Loop 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 execution, result fetching, and cleanup:

$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 name, credentials, and table structure should be adjusted to match your actual environment.

Summary

This article introduced how to use mysqli_fetch_assoc to retrieve query results: connecting to the database, executing a SELECT statement, and iterating over the result set with an associative array, enabling efficient backend data handling in PHP.

backendSQLDatabaseMySQLPHPmysqli
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.