In PHP, what are the best practices for handling database errors and ensuring data consistency when querying for existing records?

When querying for existing records in a database, it is important to handle potential errors gracefully to ensure data consistency. One best practice is to use try-catch blocks to catch any exceptions that may occur during the database query. Additionally, using transactions can help maintain data integrity by ensuring that multiple database operations either all succeed or all fail.

try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $pdo->beginTransaction();
    
    $stmt = $pdo->prepare("SELECT * FROM mytable WHERE id = :id");
    $stmt->bindParam(':id', $id);
    $stmt->execute();
    
    $result = $stmt->fetch();
    
    $pdo->commit();
    
    // Handle the fetched result here
    
} catch (PDOException $e) {
    $pdo->rollBack();
    echo "Database Error: " . $e->getMessage();
}