Welcome Guest, Not a member yet? Register   Sign In
$this->db->error()
#1

Hi,

Just upgraded to CI 3 and am having some issues with db errors on insert.

I would like to catch when the error is a duplicate error then redirect the user to a duplicate warning page. If not duplicate, I send to a success or failed page dependent on $this->db->affected_rows(). I've tried a few things but can't seem to get it right. Any help on the code below would be great.

Code:
$this->db->insert('instrument', $data);
                
                $error = $this->db->error();
                 if (isset($error['message'])) {
                    return $error['message'];
                }
               if ($error['code'] == 1062) {
                    redirect('/instruments/duplicate', '');
                } else {
                    $affected = $this->db->affected_rows();

//echo $affected;exit();

                    if ($affected > 0) {
                        redirect('/instruments/addSuccess', '');
                    } else {
                        redirect('/instruments/addFail', '');
                    }
                }

Thanks!
Reply
#2

First, the insert() method returns false on an error, so you can start by checking the returned value. Then, you can check the $error['code'] value and redirect to instruments/duplicate if it matches your error code. If you haven't redirected yet, you can return the $error['message'] if it is set. Finally, you can redirect to instruments/addFail, since you have no other options in your original code.

PHP Code:
if ($this->db->insert('instrument'$data)) {
    
redirect('instruments/addSuccess');
}

$error $this->db->error();
if (
$error['code'] == 1062) {
    
redirect('instruments/duplicate');
}

if (isset(
$error['message'])) {
    return 
$error['message'];
}

redirect('instruments/addFail'); 
Reply
#3

Thanks for the reply. You got me thinking and with everything else I read and knowing the code was right, I re-arranged the logic and turned $db['db_debug'] => FALSE and it's as desired now.

Keep well.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB