How can PHP developers optimize their code by using fetchAll() instead of a while loop when fetching data from a database using PDO?

When fetching data from a database using PDO in PHP, developers can optimize their code by using the fetchAll() method instead of a while loop. fetchAll() retrieves all rows from a result set at once, reducing the number of database round trips and improving performance.

// Using fetchAll() to optimize code when fetching data from a database using PDO
$stmt = $pdo->prepare("SELECT * FROM users");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($results as $row) {
    // Process each row as needed
}