What role does PHP play in ensuring data integrity and consistency in database operations?

PHP plays a crucial role in ensuring data integrity and consistency in database operations by allowing developers to use transactions. Transactions help maintain data integrity by ensuring that all database operations are completed successfully before committing the changes to the database. This helps prevent data corruption and inconsistencies in the database.

// Start a transaction
$pdo->beginTransaction();

try {
    // Perform database operations
    $pdo->query("UPDATE table SET column = 'value' WHERE id = 1");
    
    // Commit the transaction
    $pdo->commit();
} catch (PDOException $e) {
    // Rollback the transaction if an error occurs
    $pdo->rollBack();
    echo "Error: " . $e->getMessage();
}