To use transactions with PDO in PHP to ensure data consistency, you can follow these steps:
$dsn = 'mysql:host=example.com;dbname=mydb';
$username = 'your_username';
$password = 'your_password';
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
beginTransaction
method on the PDO object.$pdo->beginTransaction();
try {
// Perform your database operations
$pdo->commit(); // Commit the transaction if all operations succeed
} catch (PDOException $e) {
$pdo->rollBack(); // Rollback the transaction if any operation fails
throw $e; // By throwing the exception again, it can be caught and handled by an outer try-catch block
}
If all operations within the transaction are successful, call the commit
method to permanently save the changes to the database. If any operation fails, an exception will be thrown, and the transaction will be rolled back automatically, undoing any changes made within the transaction.
If an exception is caught, calling the rollBack
method will undo any changes made within the transaction and revert the database back to its original state before the transaction started.
By using transactions, you can ensure data consistency by either committing all changes if they are successful or rolling back if any operation fails. This helps maintain the integrity of your data and prevents partial changes from being saved to the database.