How to Iterate Through PDO Fetch Results Multiple Times?

Barbara Streisand
Release: 2024-10-30 07:52:28
Original
684 people have browsed it

How to Iterate Through PDO Fetch Results Multiple Times?

Resetting Iterator for Repeated Array Traversal in PDO

PDO provides a more robust and object-oriented approach for database interactions. When transitioning from MySQL SELECT methods to PDO, resetting the array pointer to iterate through fetched results multiple times can be challenging.

To achieve this in MySQL, mysql_data_seek($result, 0) is used. With PDO, a simple pointer reset is not supported. Instead, you need to consider a different approach.

Solution: Store and Re-loop an Array

The solution lies in storing the fetched results into an array and then looping through the array twice. By doing so, you break away from the PDO iterator and gain control of the array's internal pointer.

Here's how it's done:

<code class="php">$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 of the loop
}

foreach ($rows as $r) {
    // Second run of the loop
}</code>
Copy after login

This approach avoids the complexities of resetting the PDO iterator and provides a more straightforward solution for iterating through fetched results multiple times.

The above is the detailed content of How to Iterate Through PDO Fetch Results 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!