Home > Backend Development > PHP Tutorial > How do I iterate over a MySQL result set using a foreach loop?

How do I iterate over a MySQL result set using a foreach loop?

DDD
Release: 2024-11-09 10:24:02
Original
571 people have browsed it

How do I iterate over a MySQL result set using a foreach loop?

Accessing MySQL Result Set Data with a Foreach Loop

Given a MySQL result set returned as a multidimensional array, it may be used as a result of the mysql_fetch_assoc() function. However, one may encounter difficulties when attempting to iterate through it using a foreach loop.

The key lies in utilizing associative arrays to retrieve the desired data. This method is more efficient than redeclaring foreach loops within each other, which can lead to performance issues.

foreach ($rows as $row) {
    echo $row['id'];
    echo $row['firstname'];
    echo $row['lastname'];
}
Copy after login

In this example, the $rows variable represents the multidimensional array containing the result set data. Each iteration of the foreach loop assigns the current row to the $row variable, which is then accessed using associative keys ('id', 'firstname', and 'lastname').

By employing associative arrays, we can simplify the iteration process and efficiently access the required data from the result set.

The above is the detailed content of How do I iterate over a MySQL result set using a foreach loop?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template