Database Transactions In Codeigniter

Codeigniter
Transactions

A Single Transaction have group of actions or tasks and grouped into single execution unit.  Result of transaction is either success or failure. If any task or action fails, then transaction fails and all actions or tasks succeeds, the transaction success. Rollback and commit is depends on the result of transaction status.

Commit: All changes are recorded in the database are called commit.

Rolledback : Aborting or reverse the changes.

Codeigniter allows developers to commit and rollback commands by manually or automatically.

To run transaction

To run queries using transactions, You can run as many queries as you want between the start/complete functions and they will all be committed or rolled back based on success or failure of any given query.

 

$this->db->trans_start(); //Starts the transaction
...//queries
$this->db->trans_complete(); //Complete the transaction

 

Example

$this->db->trans_start();
$this->db->query('Update Country Short_name="IN" where id=1 ');
$this->db->query('Insert into states values(10,'Delhi','IN',1)');
$this->db->trans_complete();

commit and rolled back is depends on the success and failure of the quires.


run transactions manually

Use $this->db->trans_begin() instead of $this->db->trans_start() to run the transaction manually.

 

$this->db->trans_begin();

$this->db->query('query 1');
$this->db->query('query2');
$this->db->query('query3');

if ($this->db->trans_status() === FALSE)
{
        $this->db->trans_rollback();
}
else
{
        $this->db->trans_commit();
}
Strict mode

If you run multiple transactions by enabling strict mode and any group of transaction is failed then all groups will be rolled back. By default codeigniter run strict mode.

To enable strict mode

$this->db->trans_strict(TRUE);

To disable strict mode

$this->db->trans_strict(FALSE);

Leave a Reply

Your email address will not be published. Required fields are marked *