What potential pitfalls should be considered when trying to iterate over database records in PHP using a foreach loop?

One potential pitfall when iterating over database records in PHP using a foreach loop is memory consumption. If the dataset is large, loading all records into memory at once can lead to memory exhaustion. To mitigate this issue, consider fetching records in batches or using a cursor to iterate over the dataset without loading it all into memory at once.

// Example of fetching records in batches to avoid memory exhaustion
$batchSize = 1000;
$offset = 0;

do {
    $records = $db->query("SELECT * FROM table LIMIT $offset, $batchSize")->fetchAll();

    foreach ($records as $record) {
        // Process each record
    }

    $offset += $batchSize;
} while (count($records) > 0);