Home > Backend Development > PHP Tutorial > How to Iterate Through a PDO Result Set Multiple Times?

How to Iterate Through a PDO Result Set Multiple Times?

Mary-Kate Olsen
Release: 2024-10-29 14:56:02
Original
976 people have browsed it

How to Iterate Through a PDO Result Set Multiple Times?

Reiterating Through a PDO Result Set from the Beginning

When transitioning from MySQL SELECT methods to PDO methods, resetting the array pointer to iterate through the result set multiple times can be challenging. This is due to the difference in how these methods handle array pointers.

In the provided code, the first while loop successfully iterates through the fetched array starting from row zero. However, the second while loop returns an empty set since PDO's fetch() method advances the array pointer on each call.

To achieve the desired behavior, one can store the results in an array and then iterate through that array multiple times. Here's an example:

$pdo = new PDO('mysql:host=' . $host . ';dbname='.$database, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare('SELECT * FROM mytable WHERE active = 1 ORDER BY name ASC');
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();

$rows = $stmt->fetchAll();

foreach ($rows as $r) {
    // first run
}

foreach ($rows as $r) {
    // second run
}
Copy after login

By using fetchAll(), all rows from the result set are stored in the $rows array. This allows you to iterate through the array multiple times without resetting the array pointer manually.

The above is the detailed content of How to Iterate Through a PDO Result Set Multiple Times?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template