处理重复条目的错误 - PHP MySQL [英] Handle error for duplicate entries - PHP MySQL
问题描述
我想提醒用户他们需要输入一个不同的值。只是一个回声的消息或某事。
我猜我的问题归结为:
如何将特定的MySQL错误转换成PHP消息
感谢
编辑:nickf的
为了检查这个具体的错误,你需要以查找错误代码。重复键为 1062
。然后使用 errno()$的结果c $ c>
进行比较:
mysql_query('INSERT INTO ...');
if(mysql_errno()== 1062){
print'no way!';
}
编程风格说明
您应该始终设法避免使用魔术数字(我知道,我是在这个答案中介绍的)。相反,您可以将已知错误代码( 1062
)分配给常量(例如 MYSQL_CODE_DUPLICATE_KEY
)。这将使您的代码更容易维护,因为中的条件,如果
语句在几个月内仍然可读,当 1062
从内存中消失:)
I have a PHP form which 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. I guess my question comes down to: how to turn a specific MySQL error into a PHP message Thanks
edit: nickf's answer below is nice, but is there any way to discern between specific errors?
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:
mysql_query('INSERT INTO ...');
if (mysql_errno() == 1062) {
print 'no way!';
}
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. MYSQL_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 :)
这篇关于处理重复条目的错误 - PHP MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!