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
Susan SarandonOriginal
2024-12-01 22:10:12342browse

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) {
    // ...
}

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!

Statement:
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