简体   繁体   中英

Transactions in codeigniter controller?

I am using Codeigniter 2.1.4 and trying to implement a transaction. I may be missing the point of transactions, but what I'm trying to do is upload a file to my server, and create a database entry for that file. if either the row insertion or the file upload fails, i'd like to not do either.

this is the gist of my controller

first open the transaction

$this->db->trans_begin();

add entry with model

$fileId = $this->file_model->addFile('someinfo');

perform file upload

$upload = $this->upload->do_upload('file');

check to make sure both passed

//commit
if($fileId AND $upload){
    $this->db->trans_commit();
}

//rollback
else{
    $this->db->trans_rollback();
}

the transactions don't work, and the database entry is added every time, no matter if the upload fails or not.

now from previous reading, it seems like transactions belong in the model, but that doesn't work for me since i'm also uploading a file.

thoughts on how to implement this?

Try this:

$this->db->trans_start();

    //Your code Here...

$this->db->trans_complete();

$trans_status = $this->db->trans_status();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM