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

How to Reset PDO Result Array Pointer for Multiple Iterations?

Barbara Streisand
Release: 2024-12-08 20:06:16
Original
867 people have browsed it

How to Reset PDO Result Array Pointer for Multiple Iterations?

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:

  1. Save Results to an Array:

    • Execute the PDO query and store the results in an array by calling $stmt->fetchAll().
  2. Iterate Array Twice:

    • Iterate through the $rows array twice, performing the desired operations within each iteration.

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
}
Copy after login

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!

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