Welcome Guest, Not a member yet? Register   Sign In
using transactions
#1

I've read the docs on db transactions and also the db driver reference to try and get a grip on how transactions work in CodeIgniter and, although I have often used MySQL transactions, I'm still a bit confused.

In particular, it doesn't look like CI doesn't offer any function to force a ROLLBACK. I understand from the docs that "queries will all be committed or rolled back based on success or failure of any given query" but I do not see how I might force a rollback based on some non-query condition. Can someone explain how I can force a rollback?

The docs refer to trans_begin but this function is not documented in the db driver reference.

Most importantly, I want to know how to use transactions in my registration handler. When a user registers, I need to run some functions and insert records into 3 different db tables and I need to check some other stuff too. My transaction section looks something like this:
PHP Code:
try {
    
// i'd like to start the transaction here

    
$user = new User($userData);
    if (!
$user->create_db_record($this->db)) {
        throw new 
Exception("Unable to create user record");
    }
    
$userProfile = new UserProfile($userProfileData);
    if (!
$userProfile->create_db_record($this->db)) {
        throw new 
Exception("Unable to create user profile record");
    }
    
$userPhone = new UserProfile($userPhone);
    if (!
$userPhone->create_db_record($this->db)) {
        throw new 
Exception("Unable to create user phone record");
    }

    if (
$foo != $bar) {
        
// note this has nothing at all to do with any queries
        
throw new Exception("OH DANG ARBITRARY FAIL!");
    }

    
// i'd like to commit the transaction here

} catch (Exception $e) {
    
// oh no! might need to rollback that transaction if any was started
    
show_error("An exception was caught");


Can someone help me understand how to use transactions in this context?
Reply


Messages In This Thread
using transactions - by sneakyimp - 07-13-2016, 02:20 PM
RE: using transactions - by mwhitney - 07-15-2016, 11:34 AM



Theme © iAndrew 2016 - Forum software by © MyBB