CodeIgniter Transactions

A transaction is a set of inter-dependent SQL Query/Statement that are executed in all-or-nothing mode. Transaction offer 4 feather, they are given below.

  1. Atomicity
  2. Consistency
  3. Isolation
  4. Durability

Enabling Transactions in CodeIgniter

Transaction are enabled automatically when you use $this->db->trans_start().

$this->db->trans_start(); // Transaction Enable automatically $this->db->query('First SQL Statement...'); $this->db->trans_complete();

Disable Transactions in CodeIgniter

If you want disable transactions you can do so using $this->db->trans_off().

$this->db->trans_off()

Transactions Example

To run your queries using transactions in CodeIgniter you will use the $this->db->trans_start() and $this->db->trans_complete() functions.Below is simple example of transaction in CodeIgniter.

$this->db->trans_start();
$this->db->query('First SQL Statement...');
$this->db->query('Second SQL Statement...');
$this->db->query('Third SQL Statement...');
$this->db->trans_complete();

In above example we have run three query,they will all be committed or rolled back based on success or failure of any given query.

Strict Mode in CodeIgniter

By default In CodeIgniter Strict Mode is enabled.If you are running multiple groups of transactions in this mode, if one group fails all groups will be rolled back. If we disabled Strict Mode ,one transactions group will not affect any others.

To disable Strict Mode we use below code.

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

Running Transactions Manually in CodeIgniter

You can also perform transactions manually as follows.

$this->db->trans_begin();
$this->db->query('First SQL Statement...');
$this->db->query('Second SQL Statement...');
$this->db->query('Third SQL Statement...');
if ($this->db->trans_status() === FALSE)
{
    $this->db->trans_rollback();
}
else
{
    $this->db->trans_commit();
}