Home >Database >Mysql Tutorial >How Can I Reset Array Pointers in PDO After Fetching MySQL Results?
Managing Array Pointers in PDO Results
When transitioning from MySQL to PDO, handling array pointers to navigate through results can be challenging. To effectively iterate through a fetched array multiple times, starting from row zero each time, consider the following technique.
PDO does not provide a direct equivalent to the MySQL mysql_data_seek() function for resetting the array pointer. However, you can store the fetched results in an array and iterate through it as many times as needed.
Here's an updated code snippet that demonstrates this approach:
$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, starting from row zero } foreach ($rows as $r) { // Second run of the loop, starting from row zero again }
By saving the results to the $rows array, you can independently iterate through it multiple times, ensuring that each loop begins at row zero.
The above is the detailed content of How Can I Reset Array Pointers in PDO After Fetching MySQL Results?. For more information, please follow other related articles on the PHP Chinese website!