Home >Database >Mysql Tutorial >How Can I Iterate Through a PDO Result Array Twice?
Iterating an Array Twice from a PDO Result
When working with PDO, it may be necessary to iterate over a fetched array multiple times. However, unlike MySQL's mysql_data_seek() method, PDO does not provide a direct way to reset the array pointer. To accomplish the same functionality, an alternative approach must be employed.
The solution lies in storing the fetched results into an array and then iterating over that array twice. 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) { // seconds run }
In this revised code:
By saving the results into an array, the original intention of iterating over the same array twice, starting with row zero each time, is preserved. This method provides a robust and efficient solution for working with PDO results.
The above is the detailed content of How Can I Iterate Through a PDO Result Array Twice?. For more information, please follow other related articles on the PHP Chinese website!