I am attempting to run a mysqli query via php that will update an item's quantity based on what was selected. So if a user chooses two quantity of an item, that quantity should go down by two. I can successfully do this without issue with this code:
$postparts = $_POST['part_name']; <-- This is an array of the items chosen
$postqty = $_POST['qty']; <-- This is an array of the qty of each item chosen
$combine = array_combine($postparts, $postqty); <-- I combine the arrays to match the qty to the item that was chosen.  
foreach ($combine as $part=>$qty)
    {
        $update = <<<SQL
UPDATE `Houston` SET `qty` = (`qty`-?) WHERE `partnumber` = ?;
SQL;
        $result = $mysqli->prepare($update);
        $result->bind_param("is", $qty, $part);
        $result->execute();
    }
The above code will subtract the appropriate qty from the item chosen - no issue here. However, I need to implement an additional check so that if two people were to check out the same item at the same time, the first would get a successful result, but if the qty of the item is then 0 due to the first checkout process, the second person would get a failure. I tried doing that like this:
$postparts = $_POST['part_name'];
$postqty = $_POST['qty'];
$partarray = array();
foreach ($postparts as $part => $id)
{
    $finalpart = ($postparts[$part]);
    $stuff = explode(',', $finalpart);
    $partarray = array_merge($partarray, $stuff);
}
$combine = array_combine($postparts, $postqty);
$in = implode(',', array_fill(0, count($partarray), '?'));
$check = <<<SQL
SELECT * FROM `Houston` WHERE `partnumber` in ($in);
SQL;
$statcheck = $mysqli->prepare($check);
$statcheck->bind_param(str_repeat('s', count($partarray)), ...$partarray);
$statcheck->execute();
$statcheck->store_result();
$statcheck->bind_result($id, $partcat, $partnumber, $partqty);
while ($statcheck->fetch())
{
    if ($partqty > 0)
    {
        foreach ($combine as $part=>$qty)
        {
            $update = <<<SQL 
UPDATE `Houston` SET `qty` = (`qty`-?) WHERE `partnumber` = ?;
SQL;
            $result = $mysqli->prepare($update);
            $result->bind_param("is", $qty, $part);
            $result->execute();
        }
   }
   if ($partqty == 0)
   {
        header("location:error.php");
   }
}
So this "almost" works - except that the foreach loop is getting run multiple times. Say if the user checks out two items - then the foreach loop gets run twice as many times - so quantities ordered end up doubling for each item (if 3 items, then quantities are tripled, etc). I suspect the reason for this behavior is because I am running the foreach loop within the while loop, but I am not sure how I can fix this to make it work properly. Anyone know how?
 
    