Home >Database >Mysql Tutorial >How Can I Iterate Through a PDO Result Array Twice?

How Can I Iterate Through a PDO Result Array Twice?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-28 17:57:13754browse

How Can I Iterate Through a PDO Result Array Twice?

Iterating an Array Twice from a PDO Result

When working with PDO, it may be necessary to iterate over a fetched array multiple times. However, unlike MySQL's mysql_data_seek() method, PDO does not provide a direct way to reset the array pointer. To accomplish the same functionality, an alternative approach must be employed.

The solution lies in storing the fetched results into an array and then iterating over that 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) {
    // seconds run
}

In this revised code:

  • The query results are fetched into an array using fetchAll().
  • Two separate foreach loops are used to iterate over the array twice.

By saving the results into an array, the original intention of iterating over the same array twice, starting with row zero each time, is preserved. This method provides a robust and efficient solution for working with PDO results.

The above is the detailed content of How Can I Iterate Through a PDO Result Array Twice?. 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