0

I am using codeigniter for my server side in php.

I set my email field UNIQUE on my Users table. The problem is that whatever I tried I can't catch the error mysql generated when trying to insert a duplicate email.

What i tried inside my model:

function insert($arr) {

    $query=  $this->CI->db->insert('user', $arr);
    if($query){
        return $this->CI->db->insert_id();
    } else {
        $msg = $this->CI-db->_error_message();

    return  $msg;

    }

}

The issues goes that everything is fine until I get a duplicate and I actually get NOTHING inside the $msg. I know debug is on from the database config file.

Shaiful Islam
  • 7,034
  • 12
  • 38
  • 58
Dror
  • 1,262
  • 3
  • 21
  • 34

1 Answers1

2

If your database config 'db_debug' => TRUE, your code will exit with showing the error message and you will not able to reach this line $msg = $this->CI-db->_error_message();.

So to catch the error message you need to set the.

db_debug' => FALSE

At CI-2 your above code will work.See more at this question

But At CI-3 those function is not available and it will produce php undefined method error. CI-3 has a method display_error. You can check it.

My solution: If you want the errors you can get it using this line

$msg = $this->db->conn_id->error_list;

This will give you the error lists as array.But remember you need to set db_debug' => FALSE

Community
  • 1
  • 1
Shaiful Islam
  • 7,034
  • 12
  • 38
  • 58
  • how do i work with error_list when i try to return it i get "Message: Array to string conversion". i just want to return it and print to screen. – Dror May 11 '15 at 03:43
  • 2
    yes it returns array of all errors.If you want last error you can use `$this->db->conn_id->error` your case it should be `$this->CI->db->conn_id->error`. – Shaiful Islam May 11 '15 at 04:35
  • @ShaifulIslam Any idea why db_debug 'production' ENVIRONMENT default value ('db_debug' => (ENVIRONMENT !== 'production') is set to FALSE in fresh downloaded CI v3? I see that setting it to false will show db error more details, which is not expected in production, right? I'm confused because in explanation of variables (config/database.php): ['db_debug'] TRUE/FALSE - Whether database errors should be displayed. But in fact, FALSE shows the database errors. – Jeaf Gilbert Aug 24 '19 at 18:15
  • `db_debug' => TRUE` shows the error. and `FALSE` do not shows the error. `ENVIRONMENT !== 'production'` is true because default environment is development and shows the errors.Obvious you do not want to show errors on your production environment. – Shaiful Islam Aug 24 '19 at 21:36