Home >Database >Mysql Tutorial >How Can I Reset Array Pointers in PDO After Fetching MySQL Results?

How Can I Reset Array Pointers in PDO After Fetching MySQL Results?

Susan Sarandon
Susan SarandonOriginal
2024-11-28 21:06:131001browse

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!

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