What are the advantages of using PDO (PHP Data Objects) for database operations in PHP compared to traditional methods?

When performing database operations in PHP, using PDO (PHP Data Objects) offers several advantages over traditional methods like the mysql extension. PDO provides a consistent interface for accessing different types of databases, allowing for easier code maintenance and portability. Additionally, PDO supports prepared statements, which help prevent SQL injection attacks by automatically escaping input data.

// Example PHP code using PDO for database operations
try {
    $pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
    $stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
    $stmt->bindParam(':id', $userId, PDO::PARAM_INT);
    $stmt->execute();
    
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Use $user data as needed
} catch (PDOException $e) {
    echo 'Error: ' . $e->getMessage();
}