How can the use of fetchAll in PDO be optimized for better performance in PHP?

Using fetchAll in PDO can sometimes lead to performance issues when dealing with large result sets, as it fetches all rows at once into memory. To optimize performance, consider using fetchAll with the PDO::FETCH\_LAZY option, which fetches rows one at a time as needed. This can help reduce memory usage and improve overall performance when working with large datasets.

$stmt = $pdo->query("SELECT * FROM table");
$stmt->setFetchMode(PDO::FETCH_LAZY);
$results = $stmt->fetchAll();
foreach ($results as $row) {
    // process each row as needed
}