phpmysqlcodeignitersql-insertmysql-error-1062

Dealing with duplicate keys in codeigniter mysql insert


What I want to do is something like this:

function registerUser($username, $password){

$this->db->insert('tblUsers', array('username'=>$username, 'password'=>md5($password)));
if($this->db->_error_number()==1062){
    return "DUPLICATE";
}
return true;

}

However, at the moment if there is a duplicate key then its not letting me get to the _error_number() bit. Its displaying an error like this:

enter image description here

How do I stop codeigniter from bailing with an error and passing the error number to me to deal with appropriately?

Thanks


Solution

  • You can access MySQL error messages in Codeigniter using:

    $this->db->_error_message();
    

    Apparently DB_DEBUG needs to be set to false in the database config file:

    Ensure DB_DEBUG is set to FALSE in the database config file, or execution will halt when a mysql error occurs (it does not get thrown, it justs exits from the php interpreter)

    Link: http://codeigniter.com/forums/viewthread/79950/#413830