可能重複:
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));}
在您的模式中使用唯一鍵 – hohner
您可以在插入之前進行SELECT操作,包括所有這些$ _POST變量在WHERE條件中。 –
只需注意,從php 5.5.0 http://php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated開始不推薦使用'mysql'擴展名。如果這是新代碼,那麼你現在可能想要開關。 –