2013-01-21 99 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

相关问题