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

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 :)

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

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

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)