Accessing MySQL Result Set Data Using a Foreach Loop
When querying a MySQL database using PHP, the result set is often returned as a multidimensional array. Each row in the array represents a record from the database, with the columns in each row being stored as associative keys.
To iterate through such a multidimensional array using a foreach loop, you can access the rows directly using their associative indices. For example:
foreach ($rows as $row) { echo $row['id']; echo $row['firstname']; echo $row['lastname']; }
In this example, $rows is a variable holding the result set array. The foreach loop iterates through each row in the array, extracting the values for the id, firstname, and lastname columns using their associative indices.
It's important to note that nesting foreach loops is not necessary when accessing multidimensional arrays in this manner. The associative indices provide a straightforward way to retrieve the desired data without the need for additional loops or advanced array manipulation techniques.
The above is the detailed content of How Do I Iterate Through MySQL Result Set Data Using a Foreach Loop?. For more information, please follow other related articles on the PHP Chinese website!