How to use transactions with PDO to ensure data consistency in PHP?

To use transactions with PDO in PHP to ensure data consistency, you can follow these steps:

  1. Connect to the database using PDO by creating an instance of the PDO class and passing in the necessary database connection details.
$dsn = 'mysql:host=example.com;dbname=mydb'; $username = 'your_username'; $password = 'your_password'; $pdo = new PDO($dsn, $username, $password);
  1. Set the PDO error mode to throw exceptions so that any SQL errors will be caught and handled properly.
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1. Begin a transaction by calling the beginTransaction method on the PDO object.
$pdo->beginTransaction();
  1. Perform your database operations within the transaction. This can include executing multiple queries, updates, inserts, and deletes.
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 }
  1. 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.

  2. 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.