0

我想修改我的代码,而不是仅仅在 MySQL 表中插入一个新行,它可以检查是否有一个具有相同项目编号的行,然后更新它。

php代码

    <?php
    $con=mysqli_connect("localhost","root","root","inventory");

    // Check connection
    if (mysqli_connect_errno($con))
      {
       echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }



     $sql = "INSERT INTO `current stock` (ItemNumber, Stock)
               VALUES
             ('".$_POST['ItemNumber']."', '".$_POST['Stock']."' )";

    if (!mysqli_query($con,$sql))
      {
      die('Error: ' . mysqli_error($con));
      }
     echo "1 record added";


     mysqli_close($con);
     ?>
4

1 回答 1

1

您可以使用ON DUPLICATE KEY UPDATE语法,

$sql = "
   INSERT INTO `current stock` (ItemNumber, Stock)
   VALUES ('$_POST[ItemNumber]', '$_POST[Stock]' )
   ON DUPLICATE KEY UPDATE
   Stock = '$_POST[Stock]'
";

ItemNumber在这种情况下应该是主键/唯一键

于 2013-06-26T16:57:42.977 回答