doo58088 2013-01-30 17:10
浏览 45
已采纳

PHP MySQLi错误处理1062重复键输入

How can I elegantly catch the column name(s) a 1062 error code (duplicate key entry) occurred on?

When I do:

$db = @new mysqli('localhost', 'root', '******', 'database');

$pstmt = $db->prepare("INSERT INTO users (person_id, user_name, password, e_mail) VALUES (LAST_INSERT_ID(), ?, ?, ?)");
$pstmt->bind_param("sss", $_POST["register_user_name"], md5($_POST["register_password"]), $_POST["register_e_mail"]);
// error occurred
if (!$pstmt->execute()) {
    if ($db->errno == 1062) {
      $column_duplicate_key_entry = /*how to obtain the column name(s)?*/;
    }
}

Unique columns are user_name and e_mail

I know I could get the error string by calling $db->error and parsing the fields by myself. But that's not elegant in my opinion. Is there any other better solution?

What I want to do is to try to insert a new user. If the inserted user name already exists an 1062 error is thrown, so it is when the e-mail address already exists. I want to check if only the user name is taken, or only the e-mail address, or maybe both. To say it again, I want to do it on a elegant way without to select the e-mail and user name first and to check if they already exist. If possible I would like to do ONE insert query and get all information out of it.

  • 写回答

1条回答 默认 最新

  • dourang8305 2013-01-30 19:27
    关注

    MySQL returns an error in the form of a number, a state, and a message. Without parsing the message you will not be able to determine what column is duplicated.

    Furthermore, MySQL will bomb on the first failure. So, if you have user_name and e_mail as duplicates, only the first duplicate encountered will be returned in the message.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装