0

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');
?>
Shadow
  • 33,525
  • 10
  • 51
  • 64
Lyka C
  • 11
  • 2
  • 2
    Please read: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Luuk Dec 29 '22 at 12:23
  • `mysqli_query()` return a [mysqli-result](https://www.php.net/manual/en/class.mysqli-result.php). You have to get the result from that . – Luuk Dec 29 '22 at 12:29

1 Answers1

-2

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.

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
  • hi, thanks to your answer. I tried your line of code but instead of decreasing, it increases. However, I also tried to replace the -'$stock' with -'$qty' and it successfully decreases. Thank you for this idea, it really helped me. – Lyka C Dec 29 '22 at 13:12
  • I am subtracting the qty, I misunderstood, you need to change it top plus. I will correct it. – Rohit Gupta Dec 29 '22 at 13:14