What are the benefits of using PDO over mysqli for database access in PHP, especially when dealing with legacy code?
When dealing with legacy code in PHP, using PDO over mysqli for database access provides several benefits. PDO supports multiple database drivers, making it easier to switch between different databases without changing the code significantly. PDO also provides a more secure way to interact with databases by using prepared statements, which helps prevent SQL injection attacks. Additionally, PDO is object-oriented, making it easier to work with and maintain code in the long run.
// Using PDO for database access in PHP
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $userId);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
// Do something with the user data
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}