What are the differences between fetch and fetchAll methods in PDO when retrieving data from a database table?
The main difference between fetch and fetchAll methods in PDO when retrieving data from a database table is that fetch retrieves a single row from the result set, while fetchAll retrieves all rows from the result set. Fetch returns a single row as an associative array, while fetchAll returns an array containing all rows as associative arrays. To fetch a single row from a database table using fetch method:
$stmt = $pdo->query("SELECT * FROM users");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($row);
```
To fetch all rows from a database table using fetchAll method:
```php
$stmt = $pdo->query("SELECT * FROM users");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
print_r($row);
}
Related Questions
- What are common pitfalls when configuring a SoapClient in PHP for web service calls?
- In what scenarios would it be more beneficial to handle checkbox values in PHP and echo HTML codes, rather than directly including them in the HTML form?
- What are some best practices for securely hashing passwords in PHP to avoid unexpected results?