如何摆脱数据库中数量的负值。 当我将商品的数量设置为1并购买具有1个数量的商品时,下次购买将获得错误..但是当我购买具有1个数量的商品到2时它将成功并且在数据库中我获得-1的值量。
$quantityb = mysqli_real_escape_string($connect,$_POST['quantity']);
$itemNameb = mysqli_real_escape_string($connect,$_POST['itemnameb']);
$qry = "SELECT * FROM tool WHERE itemname = '$itemNameb' AND quantity > 0";
$result = mysqli_query($connect,$qry);
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result) > 0 )
{
$newvalue = $row['quantity'] - $quantityb;
$query_update = "UPDATE tool SET quantity = '$newvalue' WHERE
itemname='$itemNameb'";
$update = mysqli_query($connect,$query_update);
}
else
{
$_SESSION['msg'] = "Item isn't Exist or Item is out of stock";
}
<form action = "" method = "post">
Item Name:<input type = "text" name = "itemnameb" required>
Quantity:<input type = "number" name = "quantity" required>
<input type = "submit" name = "submit"></td>
</form>
答案 0 :(得分:0)
$newvalue = max($row['quantity'] - $quantityb, 0);
或者,如果您想抛出错误,只需检查您要购买的数量是否小于或等于更新前的可用数量。
答案 1 :(得分:0)
最好的方法是在SQL中CHECK CONSTRAINT
。但是,如果您使用的是MySQL,CHECK
将被解析为有效语法,但不会被数据库引擎处理。
您可以对SQL查询建模,以在WHERE
条件中包含约束:
$query_update = "UPDATE tool SET quantity = quantity - $quantityb WHERE itemname='$itemNameb' AND (quantity - $quantityb) >= 0";