How to catch mysql (duplicate entry) error and display a message on screen for the user, using codeigniter?

2

How to catch the error of mysql (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

    
asked by anonymous 02.05.2018 / 21:53

1 answer

2

The solution to this problem is to get sqlstate and verify that 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 should be something like:

$msg = '';
if(!$this->db->query('INSERT....')){
   $error = $this->db->error();
   if($error['code'] == 1062){
      $msg = 'Registro duplicado';
   }
}

In order for CI to not display this giant error message you can disable it via the configuration file application / config / database.php by changing the following setting to false .

Before / Original:

'db_debug' => (ENVIRONMENT !== 'production')

Then:

'db_debug' => false

Also possible to do this in specific snippets via code, just change the 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;
    
02.05.2018 / 22:01