Transactions in php

Some RDBMSs support transactions, in which a series of database changes can be committed (all applied at once) or rolled back (discarded, with none of the changes applied to the database).

For example, when a bank handles a money transfer, the withdrawal from one account and deposit into another must happen together—neither should happen without the other, and there should be no time between the two actions. PDO handles transactions elegantly with try…catch structures

Example of transaction in php

try {
 $db = new PDO("mysql:host=localhost;dbname=banking_sys", "petermac", "abc123");
 // connection successful
}
catch (Exception $error) {
 die("Connection failed: " . $error->getMessage());
}
try {
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 $db->beginTransaction();
 $db->exec("insert into accounts (account_id, amount) values (23, '5000')" );
 $db->exec("insert into accounts (account_id, amount) values (27, '-5000')" );
 $db->commit();
}
catch (Exception $error) {
 $db->rollback();
 echo "Transaction not completed: " . $error->getMessage();
}

Leave a Comment