Tom
Tom

Reputation: 12998

Codeigniter - throw exception if database transaction fails

I am trying catch database errors within a transaction and if one occurs then rollback and throw an exception.

However, the code is stopping and displaying the db error screen before it throws the exception.

Any ideas how I can make it detect db error without stopping running the subsequent code?

try {
    $this->my_function($data);
} catch (Exception $e) {
    var_dump($e);
}

private function my_function($data)
{

    $this->db->trans_start();
    foreach($data as $reg)
    {
        $sql = $this->db->insert_string('my_table', $reg);
        if($this->db->query($sql))
        {
            continue;
        } else {
            $this->db->trans_rollback();
            throw new Exception('Exception message here...');
        }
    }
    $this->db->trans_complete();

}

Upvotes: 1

Views: 6961

Answers (1)

DerpyNerd
DerpyNerd

Reputation: 4803

This has been answered before on this question

As answered by cwallenpoole:

In application/config/database.php set

// suppress error output to the screen
$db['default']['db_debug'] = FALSE;

In your model or controller:

// try the select.
$dbRet = $this->db->select($table, $dataArray);
// select has had some problem.
if( !$dbRet )
{
   $errNo   = $this->db->_error_number()
   $errMess = $this->db->_error_message();
   // Do something with the error message or just show_404();
}

Or in you case:

private function my_function($data)
{
    $errors = array();
    $this->db->trans_start();
    foreach($data as $reg)
    {
        $sql = $this->db->insert_string('my_table', $reg);
        if($this->db->query($sql))
        {
            continue;
        } else {
            $errNo   = $this->db->_error_number()
            $errMess = $this->db->_error_message();
            array_push($errors, array($errNo, $errMess));
        }
    }
    $this->db->trans_complete();
    // use $errors...
}   

Even better

I believe this question has all the answers you need because it takes multiple inserts into account and let's you finish the once that did not return an error.

Upvotes: 1

Related Questions