2012-05-30 26 views
2

我有一個提交表單,當用戶嘗試使用重複條目提交時,它會返回MySQL錯誤#1062。作爲一個例子,錯誤狀態:識別用戶,MySQL和PHP的重複條目

Duplicate entry 'graphics' for key 'name' 

我想給用戶解釋自定義消息(純英文)爲什麼他們得到了一個錯誤,什麼特定條目導致錯誤。例如:

"Graphics" is a duplicate entry and should not be used. Please remove it and resubmit the form." 

關鍵將始終是「名稱」,但重複條目本身通常會有所不同。我需要能夠從生成的MySQL錯誤中提取特定的值,然後在其周圍包裹我的自定義消息。這怎麼能做到?

+0

你可以只把所有的名字「從數據庫字段,然後做一個比較檢查PHP中,然後打印自定義消息在開始插入數據庫之前用戶指定的值。 – Bono

+1

在創建查詢時,你不知道變量的值嗎?你不能使用它嗎? – Sirko

+0

順便說一下。請注意:請停止使用古代mysql_ *函數編寫新代碼。他們不再被維護,社區已經開始了貶值過程。相反,您應該瞭解準備好的聲明並使用PDO或MySQLi。 – Bono

回答

4

您可以嘗試進行簡單的錯誤檢查,如果發生mysql錯誤,則向用戶顯示錯誤消息。你可以嘗試這樣的事:

$rows = mysql_query("SELECT `name` from `tbl` WHERE `name` = 'graphics';"); 

if(mysql_num_rows($rows) > 0){ 
    echo '"Graphics" is a duplicate entry and should not be used. Please remove it and resubmit the form.'; 
}else{ 
    insert... 
} 
0

你可以先輸入任何數據,如果你的項目預先存在插入前檢查表。

和第二,你可以根據錯誤使用,如果其他環 像

 $check_exists = // runs the code here to check if the entry graphics already exists for the existing name 

    if ($post['name'] == ''){ 

    // error message for blank entry 

    }elseif($check_exists == true) { 

    // custom error mesage for duplicate entry 

    }else { 

    // submit the form here 

    } 
+1

雖然這個想法是正確的,但提供的代碼並不是非常有用 – Bono

+0

我在這個代碼只有方式。我對桌子結構不太清楚,我告訴他這樣做的邏輯。 – Rinzler

+0

@bono如果我們編寫simle mysql查詢,那麼任何人都會學習。他問如何做到這一點不爲他做:) – Rinzler