我有一个 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));}