user3387719 user3387719 - 1 month ago 8
MySQL Question

Is it possible to rollback function action in CodeIgniter

Suppose i wan't to insert Data into 2 different tables, in codeigniter,

for example :

  • Insert into UserProfile table: name , mail to
    (get an id and use it in the next table)

  • Insert Employees table : UserProfile_id, shifts , position.

Up to now, all is working good, what can i do if i want to commit the action only if both insertions are can i rollback in case the first insertion went well and i don't want an empty profile....
My problem is that once the first insertion is committed ,suppose something went wrong in the next insertion - i get data to one table... any ideas?


See Transactions in codeigniter.

Syntax(Given in Document as well):


$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');

if ($this->db->trans_status() === FALSE)

Make sure to use $this->db->trans_begin() when running manual transactions, NOT $this->db->trans_start().

Also see strict-mode.


For multiple models you can us this approach(my opinion), Not sure if its the only/best one:

// MODEL_x

public function functionX($data)
    return  $this->db->insert('table_x',$data);
// MODEL_y

public function functionY($data)
    return  $this->db->insert('table_y',$data);

if ($this->db->trans_status() === FALSE) {
  //log error