Php PDO Transactions - BeginTransaction,RollBack,Commit

In transaction management query  is not actually applied to database untill we does not commit the transaction.
And if any error occurs then we can rollback the transaction to the previous state.

Understanding Basic Transaction Flow 

<?php
// Begin transaction
If(success)
{
   If(success)
   {      // Commit the transaction   }
   else
   {      // Roll back the transaction   }
}
else
{
   // Rollback the transaction
}
?>

Using Php PDO we can manage transaction easily.
Here is some Explanation of How Php PDO transactions works.

PDO::beginTransaction– commit the transaction

PDO::beginTransaction() used to begin the transaction. This function will return true on success and false on error. By calling this function autocommit mode will gets turned off.
<?php
// Begin a transaction 
$obj->beginTransaction();
?> 

PDO::commit – commit the transaction

PDO::commit() is used to commit any changed made to DB via PDO object. This will return true on success and false on error.The return type is boolean. Basically this will commit a transaction and autocommit the database connection until the next beginTransaction call.
<?php
    // Begin a transaction
    $obj->beginTransaction();
    // Change the database schema
    $obj->exec("DROP TABLE books");
    // Commit the changes 
    $obj->commit();
    // Database connection is now back in autocommit mode 
?> 

PDO::rollBack – Roll back a Transaction

PDO::rollback() will rollback all changes made to database after calling beginTransaction statement and return the connection to autocommit mode.
The return type is boolean.This also return true on success and false on error.
<?php
// Begin a transaction, turning off autocommit 
$obj->beginTransaction();
// Change the database schema and some data 
$obj->exec("UPDATE books SET name = 'PhpBooks'");
// Recognize mistake and roll back changes 
$obj->rollBack();
// Database connection is now back in autocommit mode 
?>

No comments: