How do I work with transactions?

chinmay.sahoo

New member
Let’s imagine we’re trying to complete a transaction at our local bank—we need to move some money from our savings account to our checking account (to pay for that vacation, of course). Now, if a problem arises in the middle of the transaction (after you withdraw the money from the savings account, but before you deposit it into the checking account), the money will disappear, and you can forget that vacation. Or does it?


If you need to run a group of SQL queries as one operation in order to maintain the integrity of your data, then you need transactions. Almost all databases provide transaction support in one form or another, and knowing how to use transactions with PDO can help you secure that well-deserved vacation.


Solution

We start the hypothetical transaction with the PDO->beginTransaction method, and if all goes well, end it with PDO->commit. If a problem occurs, we use the PDO->rollback method to undo everything that’s taken place in the transaction:

try
{
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$dbh->beginTransaction()
;
$sql = 'INSERT INTO transactions
(acctNo, type, value, adjustment)
VALUES :)acctNo, :type, :value, :adjust)';
$stmt = $dbh->prepare($sql);
$stmt->execute(array(':acctNo'=>$acctFrom, ':type'=>$withdrawal,
':value'=>$amount, ':adjust'=>'-'));
$sql = 'INSERT INTO transactions
(acctNo, type, value, adjustment)
VALUES :)acctNo, :type, :value, :adjust)';
$stmt = $dbh->prepare($sql);
$stmt->execute(array(':acctNo'=>$acctTo,
':type'=>$deposit,
':value'=>$amount,
':adjust'=>'+'));
$dbh->commit();
}
catch (Exception $e)
{
$dbh->rollBack();
⋮ further error handling here
}
 
Back
Top