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.

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

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀