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);
Keywords
Related Questions
- What are the advantages and disadvantages of using PHP versus SQL for sorting and manipulating database results?
- Are there any best practices for sending emails from a server using PHP without relying on Outlook?
- What is the best way to sort an array of ranks in PHP in descending order based on a predefined hierarchy?