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,753
  • 72
  • 57
  • 129
Jake Ols
  • 2,792
  • 3
  • 18
  • 29

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
  • 50,217
  • 8
  • 67
  • 127