Databases 4 min read

Using mysqli_fetch_assoc in PHP to Retrieve Query Results

This tutorial explains how to connect to a MySQL database using PHP's mysqli extension, execute queries with mysqli_query, and retrieve each row with mysqli_fetch_assoc, providing complete code examples and a full script for efficient database handling.

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

In PHP, database operations are essential, and using the mysqli extension is a common approach. This article introduces how to use the mysqli_fetch_assoc function to obtain query results.

1. Connect to the Database

First, we use the mysqli_connect function to establish a connection to a MySQL database. Below is a sample code:

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

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

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

2. Query the Database

Next, we can use the mysqli_query function to execute an SQL statement. Example query:

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

After running the query, the mysqli_fetch_assoc function can fetch each row as an associative array. It returns the next row on each call 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 example demonstrates using mysqli_fetch_assoc to retrieve query results:

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

$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    die("Connection failed: " . 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 results";
}

mysqli_close($conn);

Note: Replace the database name, table name, and credentials with those appropriate for your environment.

Conclusion

This article showed how to use mysqli_fetch_assoc to fetch query results by connecting to the database, executing a query, and iterating over the result set, enabling more efficient data handling in PHP development.

DatabaseMySQLfetchPHPTutorialmysqli
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.