What are the best practices for choosing between a "while" loop and a "foreach" loop when iterating over database query results in PHP?

When iterating over database query results in PHP, it is often more efficient to use a "while" loop instead of a "foreach" loop. This is because a "while" loop fetches rows one by one from the result set, which can be more memory-efficient when dealing with large datasets. On the other hand, a "foreach" loop fetches all rows at once into an array, which can consume more memory.

// Using a while loop to iterate over database query results
$query = $pdo->query("SELECT * FROM table");

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    // Process each row here
}