PDO: Resetting Array Pointer in Results
When migrating from MySQL SELECT methods to PDO, iterating through a fetched array twice with each iteration starting from row zero poses a challenge. PDO lacks an equivalent to MySQL's mysql_data_seek() function.
Consider using the following approach:
Save Results to an Array:
Iterate 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) { // second run }
This approach effectively simulates the desired behavior of resetting the array pointer, enabling multiple iterations through the same result set.
The above is the detailed content of How to Reset PDO Result Array Pointer for Multiple Iterations?. For more information, please follow other related articles on the PHP Chinese website!