Codeigniter Transactions

前端 未结 6 1740
离开以前
离开以前 2020-11-28 07:21

I\'m using Codeigniter transactions

$this->db->trans_start();
$this->db->query(\'AN SQL QUERY...\');
$this->db->trans_complete();
         


        
6条回答
  •  自闭症患者
    2020-11-28 08:05

    Using transactions means support databases to insert data safely. So in Codeigniter we write every database related functions in the Model not in Controller.. And in your second code(which is not working)you have pointed model on there.(utils). So simple I'm sure this will not work. Because its not a insert data with model and Controller parallel. Transaction should be coded in the Model(I will write in Model in my answer).


    Load this stuffs as well

    1. Database Library
    2. Model Class
    3. URL helper
    4. Session

    Assumptions

    In your code you have used $data and $test as array. So i assume there is two array for inserting and updating data.


    Your data sets

    $data = array(
       'title' => 'My title' ,
       'name' => 'My Name' ,
       'date' => 'My date'
    );
    
    $id = 007;
    $test = array(
       'title' => $title,
       'name' => $name,
       'date' => $date
    );
    

    Your Code

    $this->db->trans_start(); # Starting Transaction
    $this->db->trans_strict(FALSE); # See Note 01. If you wish can remove as well 
    
    $this->db->insert('table_name', $data); # Inserting data
    
    # Updating data
    $this->db->where('id', $id);
    $this->db->update('table_name', $test); 
    
    $this->db->trans_complete(); # Completing transaction
    
    /*Optional*/
    
    if ($this->db->trans_status() === FALSE) {
        # Something went wrong.
        $this->db->trans_rollback();
        return FALSE;
    } 
    else {
        # Everything is Perfect. 
        # Committing data to the database.
        $this->db->trans_commit();
        return TRUE;
    }
    

    Notes

    1. By default Codeigniter runs all transactions in Strict Mode. When strict mode is enabled, if you are running multiple groups of transactions, if one group fails all groups will be rolled back. If strict mode is disabled, each group is treated independently, meaning a failure of one group will not affect any others.

提交回复
热议问题