Home  >  Article  >  Backend Development  >  How to Iterate Through PDO Fetch Results Multiple Times?

How to Iterate Through PDO Fetch Results Multiple Times?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 07:52:28684browse

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>

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!

Statement:
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