The solution to this problem is to take the sqlstate and check if it is 1062
(Duplicate entry). Use the method error()
in case of failure it returns an array with the code and the description of the error.
Your code must be something like:
$msg = '';
if(!$this->db->query('INSERT....')){
$error = $this->db->error();
if($error['code'] == 1062){
$msg = 'Registro duplicado';
}
}
In order for the CI not to display this giant error message you can disable it via configuration file application/config/database.php changing the following setting to false
.
Before/original:
'db_debug' => (ENVIRONMENT !== 'production')
Afterward:
'db_debug' => false
Also possible to do this in specific snippets via code, just change the value of the property db_debug
$msg = '';
$this->db->db_debug = false;
if(!$this->db->query('INSERT....')){
$error = $this->db->error();
if($error['code'] == 1062){
$msg = 'Registro duplicado';
}
}
$this->db->db_debug = true;
Thanks for the answer, but it didn’t work, keeps appearing "A Database Error Occurred", I’m using mysql. Error Number: 1062 Duplicate entry '123456' for key 'process' INSERT INTO process (nprocess) Filename: C:/xampp/htdocs/application/system/database/Db_driver.php Line Number: 691
– Ramiro
@Ramiro error message still appears because your environment is set to dev, when switching to production will not be displayed. There’s a way to shut it down via code, I can complement that in the answer.
– rray
can yes, please.
– Ramiro
@Ramiro edited the answers.
– rray
After you spoke I managed. Thank you very much!
– Ramiro