Home > Back-end >  I want to update the stock in the database upon clicking submit, but it stores a wrong input
I want to update the stock in the database upon clicking submit, but it stores a wrong input

Time:12-29

Here is my code to insert the checked values from checkbox to database. I intend to update the stock from another table after I click submit, but it stores an incorrect input. For ex: If I entered 5 quantity on checkout page, instead of decreasing the number of stock, it inputs a negative value of what I entered: -5.. What seems to be the problem here?

<?php
include 'config.php';
$invoice = $_POST['invoiceid'];
if(isset($_POST['submit'])){
    $checked_array=$_POST['prod'];
    
    foreach ($_POST['prodname'] as $key => $value) {
        if(in_array($_POST['prodname'][$key], $checked_array)){
            $product=$_POST['prodname'][$key];
            $price= $_POST['price'][$key];
            $qty= $_POST['qty'][$key];
            
            $amtpaid = $price * $qty;

            $query = "INSERT INTO purchasedproducts SET invoice_id='$invoice', productname='$product', quantity='$qty', amtpaid='$amtpaid'";
            $run = mysqli_query($link,$query);

            //select product_stock table
            $stock_table = mysqli_query($link, "SELECT * FROM product_stock");
            
            $stock = $row['qty_stock'] - $qty;
            $update_que = "UPDATE product_stock SET qty_stock='$stock' WHERE product_name='$product'";
            $run_update = mysqli_query($link,$update_que);
        }        
    }
}
header('Location: sample.php');
?>

CodePudding user response:

Your query is updating the column value with your "input". What you are wanting is something like this.

$update_que = "UPDATE product_stock SET qty_stock=qty_stock '$stock' WHERE product_name='$product'";

This is setting the value to its original value plus the input.

  • Related