CodeIgniter Forums
$this->db->error() - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: $this->db->error() (/showthread.php?tid=63058)



$this->db->error() - picotrain - 09-21-2015

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!


RE: $this->db->error() - mwhitney - 09-21-2015

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'); 



RE: $this->db->error() - picotrain - 09-21-2015

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.