How to capture mysql (Duplicate entry) error and display a message on the screen to the user using codeigniter?

Asked

Viewed 741 times

2

How to capture mysql error (Duplicate entry) and display a message on the screen to the user using codeigniter?

Error Number: 1062

Duplicate entry '123456' for key 'process'

INSERT INTO processo (nprocesso)

Filename: C:/xampp/htdocs/application/system/database/Db_driver.php

Line Number: 691

1 answer

2


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 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.

  • can yes, please.

  • @Ramiro edited the answers.

  • After you spoke I managed. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.