Home > Database > Mysql Tutorial > How to Reset the Array Pointer in PDO Result Sets for Multiple Iterations?

How to Reset the Array Pointer in PDO Result Sets for Multiple Iterations?

Susan Sarandon
Release: 2024-12-01 22:10:12
Original
246 people have browsed it

How to Reset the Array Pointer in PDO Result Sets for Multiple Iterations?

Resetting the Array Pointer in PDO Results

When transitioning from MySQL SELECT methods to PDO, resetting the array pointer becomes essential for iterating through fetched arrays multiple times. While MySQL offers mysql_data_seek() to accomplish this, PDO requires a different approach.

To successfully reset the array pointer in PDO, consider the following solution:

First, retrieve the result set into an array using fetchAll() method. This method fetches all rows into a PHP array. Subsequently, you can iterate over this array multiple times to access and process the data from each row.

Here's an updated 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(); // Saving results into an array

// First Iteration
foreach ($rows as $r) {
    // ...
}

// Second Iteration
foreach ($rows as $r) {
    // ...
}
Copy after login

This revised approach allows you to iterate through the result set multiple times, starting from the first row each time.

The above is the detailed content of How to Reset the Array Pointer in PDO Result Sets for Multiple Iterations?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template