Home > Article > Backend Development > How to Access MySQL Result Set Data with a Foreach Loop in PHP?
When working with MySQL in PHP, result sets are often returned as multidimensional arrays. This can present a challenge when attempting to access the data within the array using a foreach loop. However, there is a simple solution.
The key lies in understanding the structure of the multidimensional array. As an example, consider the following array structure:
$rows = [ [ 'id' => 1, 'firstname' => 'Firstname one', 'lastname' => 'Lastname one' ], [ 'id' => 2, 'firstname' => 'Firstname two', 'lastname' => 'Lastname two' ], [ 'id' => 3, 'firstname' => 'Firstname three', 'lastname' => 'Lastname three' ], ];
In this array, each element represents a row in the result set. The row data is stored in associative arrays, where the keys represent the column names (e.g. 'id', 'firstname', 'lastname').
To access the data within the array using a foreach loop, simply iterate over the outermost array and access the row data using the column names as keys:
foreach ($rows as $row) { echo($row['id']); echo($row['firstname']); echo($row['lastname']); }
This method provides a simple and efficient way to iterate over the data in a MySQL result set using a foreach loop. It eliminates the need for complex nested loops or the use of numerical indices to access the row data.
The above is the detailed content of How to Access MySQL Result Set Data with a Foreach Loop in PHP?. For more information, please follow other related articles on the PHP Chinese website!