What is the difference between using fetch() and fetchAll() in PDO prepared statements in PHP?

When using PDO prepared statements in PHP, fetch() is used to retrieve a single row from the result set, while fetchAll() is used to retrieve all rows from the result set. If you only need to retrieve a single row, fetch() is more efficient as it fetches one row at a time. If you need to retrieve multiple rows, fetchAll() is more suitable as it fetches all rows at once.

// Using fetch() to retrieve a single row
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(['id' => $id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Using fetchAll() to retrieve all rows
$stmt = $pdo->prepare("SELECT * FROM users");
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);