What precautions should be taken when interacting with databases in PHP scripts to avoid errors?

When interacting with databases in PHP scripts, it is important to properly handle errors to avoid potential issues. One precaution to take is to use try-catch blocks to catch any exceptions that may occur during database operations. Additionally, always sanitize user input to prevent SQL injection attacks.

try {
    // Connect to the database
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    
    // Prepare and execute the query
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->bindParam(':id', $userId);
    $stmt->execute();
    
    // Fetch the results
    $user = $stmt->fetch();
    
    // Close the connection
    $pdo = null;
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}