Codeigniter:当我插入数据时,我得到重复的密钥错误,我该如何处理这个错误?

时间:2017-10-09 09:50:19

标签: php codeigniter-3

当我插入数据时,我发现重复键错误,我该如何处理此错误?

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

如何处理db错误?

修改

错误呈现

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

但是,我不想向用户展示它。相反,我希望向用户显示另一条错误消息,例如:

"Such User exists. Please try again!"

1 个答案:

答案 0 :(得分:2)

您之前检查过,此类用户ID是否已存在

$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);

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');
}