CodeIgniter Forums
Can we use Database Transactions like this? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Can we use Database Transactions like this? (/showthread.php?tid=1411)



Can we use Database Transactions like this? - noobie - 03-08-2015

Hello,

In CI user guide, i only see using $this->db->query() method, are we also allowed to use "Active Record Class" like this?

PHP Code:
$data_balance = array(
 
'balance' => $newbalance
);          
$data_transaction = array(
 
'amount' => $amount,
 
'user' => $user
); 
PHP Code:
$this->db->trans_start();
 
// This is an "Insert" query for a table
 
$this->db->set('date''NOW()'FALSE);
 
$this->db->insert('financial_transactions'$data_transaction);
 
// This is an "Update" query for another table
 
$this->db->where('user_id'$user_id);
 
$this->db->update('financial_balances'$data_balance);
$this->db->trans_complete(); 
PHP Code:
if ($this->db->trans_status() === FALSE){
    
// Do stuff if failed 


Note that i use $this->db-> for both queries, so i don't know if the success result of first one is actually cleared to check the second one?

Is this going to work? can i trust that this will make either both queries to success or neither of them (i don't want one to success and one to fail)


RE: Can we use Database Transactions like this? - mwhitney - 03-09-2015

insert() and update() use query() internally to perform their functionality (they just build the query for you according to the current database driver). So, it will roll back the transaction if the insert or update fails, but the definition of failure may or may not be what you expect.