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

How to handle error for duplicate entries?(如何处理重复条目的错误?)
本文介绍了如何处理重复条目的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个 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 :)

这篇关于如何处理重复条目的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Why can#39;t I update data in an array with foreach loop?(为什么我不能用 foreach 循环更新数组中的数据?)
Foreach for arrays inside of an array(Foreach 用于数组内的数组)
PHP array get next key/value in foreach()(PHP 数组在 foreach() 中获取下一个键/值)
Using preg_match on a multidimensional array to return key values arrays(在多维数组上使用 preg_match 返回键值数组)
php foreach as key, every two number as a group(php foreach 为key,每两个数字为一组)
Treat a PHP class that implements Iterator as an array(将实现 Iterator 的 PHP 类视为数组)