問題描述
我有一個 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 :)
這篇關于如何處理重復條目的錯誤?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!