Home > Database > Mysql Tutorial > How to Iterate Over a MySQL Result Set Multiple Times in PHP?

How to Iterate Over a MySQL Result Set Multiple Times in PHP?

DDD
Release: 2024-12-24 04:11:22
Original
878 people have browsed it

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:

  1. 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;
    }
    Copy after login

    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);
    Copy after login
  2. Iterate over the Stored Data:

    Now, you can iterate over the stored data in the array for output:

// Top row
foreach ($data as $row) {
Copy after login

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!

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