1

When I insert data I'm getting duplicate key error, how can I handle this error?

if($this->db->insert('user', $this)) {
  return TRUE;
}

how can I handle db errors?

EDIT

This is the error presented:

A Database Error Occurred

Error Number: 1062

Duplicate entry 's123' for key 'login'

INSERT INTO `user` (`id`, `login`, `hash`, `fname`, `sname`, `lname`, `phone`, `email`, `administrator`, `moderator`, `author`, `add_time`, `is_active`) VALUES (NULL, 's123', '$2y$10$EIrEBovWdrSPnMKNOvBuyebUnQKaKNePQSOmhyihf124tompkSnQK', 's123', 's123', 's123', '123', 's123', '0', '0', '0', 1507543679, '0')

Filename: models/User_model.php

Line Number: 74

But, I don't want to show it to user. Instead, I want present the user another error message, like:

"Such User exists. Please try again!"

11
  • auto increment the id or primary key Commented Oct 9, 2017 at 9:51
  • 2
    don't pass primary key while inserting. if you don't have primary key in table then make table id as auto incremented primary key Commented Oct 9, 2017 at 9:51
  • @BilalAhmed: id is primary key and auto_increment, but I want to handle mysql error Commented Oct 9, 2017 at 9:51
  • I need equiv of mysqli_error() in codeigniter? Commented Oct 9, 2017 at 9:54
  • use try catch there Commented Oct 9, 2017 at 9:55

1 Answer 1

4

Either you check before, whether such user id exists already

$query = $this->db->get_where('user', array(
            'id' => $user_id
        ));

$count = $query->num_rows(); 

if($count){
     $this->session->set_flashdata('error', 'Such User exists. Please try again!');
     redirect('controller_name/method_name');
}

// if above one does not evaluate true then insert
$this->db->insert('user', $some_array_with_data);

OR

try{

    $this->db->insert('user', $some_array_with_data);

}catch(Exception $e){

       // this is what you show to user,
       $this->session->set_flashdata('error', 'Such User exists. Please try again!');

      // if you want to log error then
      log_message('error',$e->getMessage());

      // redirect somewhere
      redirect('controller_name/method_name');
}
Sign up to request clarification or add additional context in comments.

7 Comments

Dear friend, thanks for response, suddenly it's didn't help ((
@SalimIbrogimov: set db_debug to FALSE in application/config/database.php and then try,
I have this: $db['default']['db_debug'] = (ENVIRONMENT !== 'production')
if you set, either ENVIRONMENT to production, or $db['default']['db_debug'] = false, then try{}catch(){} should work, otherwise, use first solution, which will work even if $db['default']['db_debug'] = true;
Thanks a lot, I did this: $db['default']['db_debug'] = FALSE;.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.