user3387719 user3387719 - 2 months ago 16
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 commited...how 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?

Answer

See Transactions in codeigniter.

Syntax(Given in Document as well):

$this->db->trans_begin();

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

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

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

Also see strict-mode.

UPDATED

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);
}

//controller
$this->db->trans_start();
$this->model_x->functionX();
$this->model_y->functionY();
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
  //log error  
}