0

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!"

Ricardo Vieira
  • 1,738
  • 1
  • 18
  • 26
Salim Ibrohimi
  • 1,351
  • 3
  • 17
  • 35

1 Answers1

3

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');
}
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36