Current Location: Home> Latest Articles> How to use mysql_fetch_array and foreach loops in combination

How to use mysql_fetch_array and foreach loops in combination

gitbox 2025-05-29

1. Basic usage of mysql_fetch_array

The mysql_fetch_array function takes a row from the result set as an array, and returns the array containing both association and index by default:

 $result = mysql_query("SELECT * FROM users");
while ($row = mysql_fetch_array($result)) {
    print_r($row);
}

Here $row is a record obtained in each loop, and the type is an array.

2. Foreach traverses the array of single records

When you get a record from mysql_fetch_array , you usually use foreach to iterate through all fields of this data:

 while ($row = mysql_fetch_array($result)) {
    foreach ($row as $key => $value) {
        echo "$key => $value<br>";
    }
}

This is correct, because $row itself is an array.

3. You cannot use foreach directly for query results

Note that mysql_fetch_array returns a single record, and cannot directly use foreach for query result resources:

 foreach ($result as $row) {
    // Wrong usage,$resultIt&#39;s a resource,Not an array
}

This writing method is wrong and will lead to an error.

4. Correct combination method: first use a while loop to read all data into the array, and then use foreach to traverse

If you want to use foreach to traverse all records, the common practice is to read all the results into an array first, and then traverse:

 $rows = [];
while ($row = mysql_fetch_array($result)) {
    $rows[] = $row;
}

foreach ($rows as $record) {
    // Process each record
    echo $record['username'] . "<br>";
}

This way, you can easily handle all records in foreach .

5. Use MYSQL_ASSOC to avoid data redundancy

The array returned by mysql_fetch_array by default has both numerical indexes and associated indexes, resulting in data redundancy. It is recommended to only get associative arrays:

 while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    // $rowContains only associative arrays
}

In this way, the array is simpler and the foreach traversal is more convenient.

6. Sample complete code

 <?php
// Connect to the database
$link = mysql_connect("gitbox.net", "username", "password");
mysql_select_db("testdb", $link);

// Query data
$result = mysql_query("SELECT id, username, email FROM users");

// Read all data
$rows = [];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $rows[] = $row;
}

// useforeachIterate through all records
foreach ($rows as $record) {
    echo "userID: " . $record['id'] . "<br>";
    echo "user名: " . $record['username'] . "<br>";
    echo "Mail: " . $record['email'] . "<br><hr>";
}

// Close the connection
mysql_close($link);
?>