How does the fetch() function differ from fetchAll() when retrieving data using PDO in PHP?
When retrieving data using PDO in PHP, the fetch() function is used to retrieve a single row of data from a result set, while fetchAll() is used to retrieve all rows of data from the result set as an array. If you only need to retrieve one row of data, you would use fetch(), but if you need to retrieve multiple rows, you would use fetchAll().
// Using fetch() to retrieve a single row of data
$stmt = $pdo->query("SELECT * FROM users WHERE id = 1");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// Using fetchAll() to retrieve all rows of data
$stmt = $pdo->query("SELECT * FROM users");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Keywords
Related Questions
- What are common pitfalls when developing a PHP website that may cause lagging, especially when viewed in Internet Explorer?
- How does the modification of the SQL query in the PHP code affect the output of the array data?
- How can HTML tags be properly integrated within PHP code to ensure valid document structure?