0

I want to modify my code so instead of just inserting a new row in the MySQL table, it can check to see if there is one with the same item number, and update it.

php code

    <?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);
     ?>
Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Jake Ols
  • 2,633
  • 3
  • 15
  • 26

1 Answers1

1

You can use ON DUPLICATE KEY UPDATE syntax,

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

ItemNumber should be primary/unique key in this case

mpapec
  • 49,466
  • 8
  • 63
  • 119