【问题标题】:Codeigniter: when I insert data I'm getting duplicate key error, how can I handle this error?Codeigniter:当我插入数据时出现重复键错误,我该如何处理这个错误?
【发布时间】:2018-03-20 11:46:30
【问题描述】:

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

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

【问题讨论】:

  • 自动增加 id 或主键
  • 插入时不要传递primary key。如果表中没有primary key,则将table id 设为auto incremented primary key
  • @BilalAhmed: id 是主键和auto_increment,但我想处理mysql 错误
  • 我需要在 codeigniter 中相当于 mysqli_error()
  • 在那里使用try catch

标签: php codeigniter-3


【解决方案1】:

你之前检查过,这样的用户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');
}

【讨论】:

  • 亲爱的朋友,谢谢回复,突然没用了((
  • @SalimIbrogimov: 在application/config/database.php 中将db_debug 设置为FALSE 然后尝试,
  • 我有这个:$db['default']['db_debug'] = (ENVIRONMENT !== 'production')
  • 如果您设置,环境为生产,或$db['default']['db_debug'] = false,那么try{}catch(){} 应该可以工作,否则,使用第一个解决方案,即使$db['default']['db_debug'] = true; 也可以工作
  • 非常感谢,我做到了:$db['default']['db_debug'] = FALSE;
猜你喜欢
  • 1970-01-01
  • 2019-12-01
  • 2020-04-25
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 2021-10-01
  • 1970-01-01
相关资源
最近更新 更多