如何处理重复条目的错误?

2021-12-26 00:00:00 error-handling php mysql

我有一个 PHP 表单,可以将数据输入到我的 MySQL 数据库中.我的主键是用户输入的值之一.当用户输入表中已存在的值时,MySQL 错误Duplicate entry 'entered value' for key 1"被退回.而不是那个错误,我想提醒用户他们需要输入不同的值.只是一个回显的消息或其他东西.

I have a PHP form that enters data into my MySQL database. My primary key is one of the user-entered values. When the user enters a value that already exists in the table, the MySQL error "Duplicate entry 'entered value' for key 1" is returned. Instead of that error, I would like to alert the user that they need to enter a different value. Just an echoed message or something.

如何将特定的 MySQL 错误转换为 PHP 消息?

How to turn a specific MySQL error into a PHP message?

推荐答案

要检查此特定错误,您需要找到 错误代码.重复键是1062.然后使用 errno() 比较:

To check for this specific error, you need to find the error code. It is 1062 for duplicate key. Then use the result from errno() to compare with:

mysqli_query('INSERT INTO ...');
if (mysqli_errno() == 1062) {
    print 'no way!';
}

关于编程风格的说明
您应该始终设法避免使用幻数(我知道,我是在这个答案中介绍它的人).相反,您可以将已知错误代码 (1062) 分配给一个常量(例如 MYSQLI_CODE_DUPLICATE_KEY).这将使您的代码更易于维护,因为 if 语句中的条件在 1062 的含义从记忆中消失后的几个月内仍然可读:)

A note on programming style
You should always seek to avoid the use of magic numbers (I know, I was the one to introduce it in this answer). Instead, you could assign the known error code (1062) to a constant (e.g. MYSQLI_CODE_DUPLICATE_KEY). This will make your code easier to maintain as the condition in the if statement is still readable in a few months when the meaning of 1062 has faded from memory :)

相关文章