What are some common pitfalls when using PDO for database queries in PHP?

One common pitfall when using PDO for database queries in PHP is not properly handling errors. It's important to check for errors after executing a query and handle them appropriately to prevent issues with the database connection. Another pitfall is not using prepared statements, leaving your code vulnerable to SQL injection attacks. Always use prepared statements to securely pass user input to the database.

// Example of handling errors and using prepared statements with PDO

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 username = :username");
    $stmt->bindParam(':username', $username);
    $stmt->execute();
    
    // Fetch results
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}