Home >Database >Mysql Tutorial >How to Iterate Over a MySQL Result Set Multiple Times in PHP?
How to Traverse mysqli Result Sets Multiple Times
When working with MySQL databases using PHP, it can be necessary to access the data returned from a query multiple times. However, using mysqli_fetch_array() twice on the same result will not work.
Solution
To overcome this limitation, separate data manipulation from output:
Select and Store the Data:
First, select the data from the database and store it in an array:
$db_res = mysqli_query( $db_link, $sql ); $data = array(); while ($row = mysqli_fetch_array($db_res, MYSQLI_ASSOC)) { $data[] = $row; }
Alternatively, you can use fetch_all() for PHP versions 5.3 and above:
$db_res = mysqli_query( $db_link, $sql ); $data = $db_res->fetch_all(MYSQLI_ASSOC);
Iterate over the Stored Data:
Now, you can iterate over the stored data in the array for output:
// Top row foreach ($data as $row) {
The above is the detailed content of How to Iterate Over a MySQL Result Set Multiple Times in PHP?. For more information, please follow other related articles on the PHP Chinese website!