2013-01-21 103 views
0

可能重複:
What is the best way to insert into and update a single row table in MySQL?
handling duplicate records in mysql Insert statement如何在數據庫中插入時檢查重複記錄

我有一個將記錄插入我的數據庫一個PHP Web表單時點擊「提交」按鈕。然而,我想如果一個記錄已經存在於具有相同主鍵(itemID)的數據庫中,插入操作將被中止,並且用戶將被警告。

我的 '插入' 代碼:

$editFormAction = $_SERVER['PHP_SELF']; 
if (isset($_SERVER['QUERY_STRING'])) { 
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);} 

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) { 
$insertSQL = sprintf("INSERT INTO inventory (itemID, name, itemcategory, qis, reorderlevel, unitcost, sellingprice, 
supplier, specifications) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", 
GetSQLValueString($_POST['itemID'], "text"), 
GetSQLValueString($_POST['name'], "text"), 
GetSQLValueString($_POST['itemcategory'], "text"), 
GetSQLValueString($_POST['qis'], "double"), 
GetSQLValueString($_POST['reorderlevel'], "int"), 
GetSQLValueString($_POST['unitcost'], "double"), 
GetSQLValueString($_POST['sellingprice'], "double"), 
GetSQLValueString($_POST['supplier'], "text"), 
GetSQLValueString($_POST['specifications'], "text")); 

mysql_select_db($database_con1, $con1); 
$Result1 = mysql_query($insertSQL, $con1) or die(mysql_error()); 

$insertGoTo = "insertsuccess.php"; 
if (isset($_SERVER['QUERY_STRING'])) { 
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?"; 
$insertGoTo .= $_SERVER['QUERY_STRING'];} 

header(sprintf("Location: %s", $insertGoTo));} 
+0

在您的模式中使用唯一鍵 – hohner

+0

您可以在插入之前進行SELECT操作,包括所有這些$ _POST變量在WHERE條件中。 –

+0

只需注意,從php 5.5.0 http://php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated開始不推薦使用'mysql'擴展名。如果這是新代碼,那麼你現在可能想要開關。 –

回答

0

如果您將ItemID列定義爲表定義中的主鍵,那麼在duplicate鍵的情況下查詢會給您一個錯誤。您可以在錯誤捕獲部分警告用戶。

注意:不推薦使用Mysql擴展,而是使用MYSQLi_ *或PDO擴展。

2

如果你正在使用MySQL存在INSERT ... ON DUPLICATE KEY UPDATE結構。

你的情況:

INSERT INTO inventory (itemID, name, itemcategory, qis, reorderlevel, unitcost, sellingprice,supplier, specifications) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE name = %s, itemcategory = %s, ....) 

這需要的itemId於表作爲唯一鍵進行定義。根據你的問題,你想要什麼。

0

您可以使用'INSERT IGNORE'語句,並檢查LAST_INSERT_ID()。如果LAST_INSERT_ID()返回0,則表示它是重複條目,並且可以提醒用戶。

+0

'LAST_INSERT_ID()'在某些情況下有效,但不是(總是)線程安全的,因此從不真正競爭條件安全。含義:它會在可同時插入東西的網站中駭人聽聞地打破。換句話說:小心使用。 – berkes

相關問題