简体   繁体   中英

if else query that I need to add to restrict users from inputting quantities higher than the stock

I want to restrict users from inputting quantities higher than the stock. The quantity of the product is from a different table, the qty below is the quantity of the product in the cart.

What would be the best approach to do this?

This is my add_cart.php

<?php
    include('session.php');
    if(isset($_POST['cart'])){
        $id=$_POST['id'];
        $qty=$_POST['qty'];

        $query=mysqli_query($conn,"select * from cart where productid='$id' and userid='".$_SESSION['id']."'");
        if (mysqli_num_rows($query)>0){
            echo "Product already on your cart!";
        }
        else{
            mysqli_query($conn,"insert into cart (userid, productid, qty) values ('".$_SESSION['id']."', '$id', '$qty')");
        }
    }

?>

This is just for demonstration purpose

<?php

    $query=mysqli_query($conn,"select * from cart where productid='$id' and userid='".$_SESSION['id']."'");

    if (mysqli_num_rows($query)>0){
        echo "Product already on your cart!";
    }
    else{
        //GET STOCK
        $query=mysqli_query($conn,"select * from table where stock = '$yourstock' ");
        $row=mysqli_fetch_array($query);
        //CHECK IF QTY IS HIGHER THAN STOCK OR NOT
        if($qty > $row['stock'] ){
            //SHOW ERROR THAT VALUE IS HIGHER THAN STOCK
        }else{
            mysqli_query($conn,"insert into cart (userid, productid, qty) values ('".$_SESSION['id']."', '$id', '$qty')");
        }
    }
<?php
include('session.php');
if(isset($_POST['cart'])){
    $id=$_POST['id'];
    $qty=$_POST['qty'];

    $query=mysqli_query($conn,"select * from product_stock_table where productid='$id'");
    if(mysqli_num_rows($query) < $qty){
       echo 'out of stock try';
    } else{
        $query=mysqli_query($conn,"select * from cart where productid='$id' and userid='".$_SESSION['id']."'");
        if (mysqli_num_rows($query)>0){
            echo "Product already on your cart!";
        }
        else{
            mysqli_query($conn,"insert into cart (userid, productid, qty) values ('".$_SESSION['id']."', '$id', '$qty')");
        }
  }
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM