In what situations would it be beneficial to use PDO and fetchAll instead of traditional mysql functions for database operations in PHP?
Using PDO and fetchAll instead of traditional mysql functions is beneficial when you need to work with different database systems, as PDO provides a consistent interface for accessing various databases. Additionally, PDO helps prevent SQL injection attacks by using prepared statements. The fetchAll method allows you to retrieve all rows from a query result in a single call, making it more efficient and convenient for processing large datasets.
// Connect to the database using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
// Prepare and execute a query
$stmt = $pdo->prepare("SELECT * FROM users");
$stmt->execute();
// Fetch all rows from the query result
$rows = $stmt->fetchAll();
// Process the retrieved data
foreach ($rows as $row) {
echo $row['name'] . "<br>";
}