【问题标题】:How to check for duplicate records in the database upon insert [duplicate]如何在插入时检查数据库中的重复记录[重复]
【发布时间】:2013-01-21 16:40:47
【问题描述】:

可能重复:
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));}

【问题讨论】:

  • 在架构中使用唯一键
  • 您可以在插入之前进行选择,包括 WHERE 条件中的所有 $_POST 变量。
  • 请注意,从 php 5.5.0 php.net/manual/en/… 开始,mysql 扩展名已被弃用。如果这是新代码,那么您可能需要现在进行切换。

标签: php database insert


【解决方案1】:

如果您使用的是 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 定义为唯一键。根据您的问题,您仍然想要哪个。

【讨论】:

    【解决方案2】:

    如果您将ItemID 列定义为表定义中的主键,则查询将在duplicate 键的情况下为您提供错误。您可以在错误捕获部分提醒用户。

    注意: 不推荐使用 Mysql 扩展,请改用 MYSQLi_* 或 PDO 扩展。

    【讨论】:

      【解决方案3】:

      您可以使用“INSERT IGNORE”语句,并检查 LAST_INSERT_ID()。如果 LAST_INSERT_ID() 返回 0,表示重复条目,可以提醒用户。

      【讨论】:

      • LAST_INSERT_ID() 在某些情况下有效,但不是(总是)线程安全的,因此永远不是真正的竞争条件安全。含义:它会在同时插入内容的网站中严重崩溃。换句话说:小心使用。
      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 2019-09-21
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      • 1970-01-01
      相关资源
      最近更新 更多