Organizational Research By

Surprising Reserch Topic

codeigniter Transactions with multiple tables


'm new to transactions in general, but especially with CodeIgniter. I'm using InnoDB and everything, but my transactions aren't rolling back when I want them to. Here's my code (slightly simplified).

            $dog_db = $this->load->database('dog', true);
            $dog_db->trans_begin();

            $dog_id = $this->dogs->insert($new_dog); //Gets primary key of insert
            if(!$dog_id)
            {
                $dog_db->trans_rollback();
                throw new Exception('We have had an error trying to add this dog.  Please go back and try again.');
            }

            $new_review['dog_id'] = $dog_id;
            $new_review['user_id'] = $user_id;
            $new_review['date_added'] = time();

            if(!$this->reviews->insert($new_review)) //If the insert fails
            {
                $dog_db->trans_rollback();
                throw new Exception('We have had an error trying to add this dog.  Please go back and try again.');
            }

                //ADD DESCRIPTION
            $new_description['description'] = $add_dog['description'];
            $new_description['dog_id'] = $dog_id;
            $new_description['user_id'] = $user_id;
            $new_description['date_added'] = time();

            if(!$this->descriptions->insert($new_description))
            {
                $dog_db->trans_rollback();
                throw new Exception('We have had an error trying to add this dog.  Please go back and try again.');
            }

                $dog_db->trans_rollback();  //THIS IS JUST TO SEE IF IT WORKS
                throw new Exception('We have had an error trying to add this dog.  Please go back and try again.');

            $dog_db->trans_commit();
}

catch(Exception $e)
{
    echo $e->getMessage();
}

asked Jun 1, 2015 in codeinither by rajesh
0 votes
74 views



Related Hot Questions

1 Answer

0 votes
Well, I know this post is antique, but here's my 2 cents:

I don't think this:

if(!$this->descriptions->insert($new_description))
will work, cause the insert function from CI active record always returns TRUE (succeeding or not). If you are using debug mode, CI will stop on error and throw a screen message to the user, but insert function will still returns TRUE.

So, if you're willing to control transactions "manualy" with CI, you'll have to use something like this:

...

$this->db->trans_begin();

$this->db->insert('FOO');

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

    $this->db->trans_rollback();

}else{

    $this->db->trans_commit();

}
answered Jun 1, 2015 by rajesh

...