Introduction
Migrating from MySQL SELECT methods to PDO methods can introduce challenges. Resetting the array pointer, which allows iterating through a fetched array multiple times, is one such challenge.
The Problem
In MySQL, the mysql_data_seek() function achieves this pointer reset. However, in PDO, this function is not available. As exemplified in the provided code, subsequent loops starting from row zero return no results.
The Solution
To overcome this issue, store the fetched results in an array and iterate over that array multiple times. This modified code demonstrates the solution:
$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) { // seconds run }
Additional Context
By implementing this solution, you can effectively reset the array pointer in PDO results, allowing you to iterate through the fetched array multiple times starting from row zero.
The above is the detailed content of How to Reset the Array Pointer in PDO Results After `fetchAll()`?. For more information, please follow other related articles on the PHP Chinese website!