What is the difference between fetch() and fetchAll() methods in PDO when retrieving data from a database in PHP?

The difference between fetch() and fetchAll() methods in PDO when retrieving data from a database in PHP is that fetch() retrieves a single row at a time, while fetchAll() retrieves all rows at once and returns them as an array. If you only need to fetch one row at a time, fetch() is more efficient. If you need to fetch all rows and work with them as an array, fetchAll() is the better option.

// Example of using fetch() method
$stmt = $pdo->query("SELECT * FROM users");
while ($row = $stmt->fetch()) {
    // Process each row individually
}

// Example of using fetchAll() method
$stmt = $pdo->query("SELECT * FROM users");
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
    // Process each row in the $rows array
}