title: PHP Issue Updating Database On Button Click
body: <p>Hello I'm making a shop in php where I populate the shop with a while loop so all the shop items from my database are displayed. This works fine but I have an issue when I try to update the stock count and money left on the account when I press the buy button. </p>
  
  <p>The $ItemCost variable only saves the last populated item cost and I'm not sure how to save the cost of each item to insert it into the database.
  Also the $StockCount variable sets the stockcount to 1.</p>
  
  <p>How can I fix this.</p>
  
  <pre><code>    &lt;?php
  
  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "useraccounts";
  
  // Create connection
  $conn = mysqli_connect($servername, $username, $password, $dbname);
  
  $GatherItems = "SELECT * FROM shopitems WHERE StockCount &gt; 0  ORDER BY`shopitems`.`Cost` DESC";
  $result = $conn-&gt;query($GatherItems);
  
  if ($result-&gt;num_rows &gt; 0) {
  // output data of each row
  
  while($row = $result-&gt;fetch_assoc()) {
      $ItemName = $row['ItemName'];
      $ItemCost = $row['Cost'];
      $ID = $row['ID'];
      $StockCount = $row['StockCount'];
      $Money = $row['Money'];
  
  echo "&lt;div class='test'&gt;$ItemName&lt;/div&gt;";
  echo "&lt;div class='test1'&gt;$ItemCost &lt;/div&gt;";
  echo "&lt;input type='submit'  class='btn btn-primary' name='Buy' value='Buy Now'/&gt;";
  }
  
  $NewTotal = $Money - $ItemCost;
  $Inventory = "UPDATE shopitems SET StockCount = $StockCount-1, Money = $NewTotal WHERE ID = $ID";
  
  if(isset($_POST['Buy'])){
  if ($conn-&gt;query($Inventory) === TRUE) {
      echo "New record created successfully";
  } else {
  echo "Error: " . $Inventory . "&lt;br&gt;" . $conn-&gt;error;
     }
  }
  }
  $conn-&gt;close();
  ?&gt;
  </code></pre>