How to loop through a mysql result set

Viewed 86082

What are some different ways to loop through a mysql result set? I'm new to PHP and MySQL so I'm looking for simple ways to loop through and an explanation as to how the provided code works.

6 Answers

In modern php, you don't need to call any functions to fetch the data of a result set. The result set object is immediately iterable and a foreach() will allow you to traverse the data as if it was an indexed array of associative arrays. (Since PHP5.4.0, circa March 1, 2012 - "MySQLi: Added iterator support in MySQLi. mysqli_result implements Traversable.")

Example:

foreach ($conn->query("SELECT one, two, three FROM my_table") as $index => $row) {
    echo "<div>$index: {$row['one']}, {$row['two']}, {$row['three']}</div>";
}
Related