尝试检查用户在表单上输入的数量是否大于库存数量。如果是,那么它应该在表格上将数量设置为STOCK VALUE。
if (isset($_SESSION["cart_array"]))
{
if (isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") {
// execute some code
$item_to_adjust = $_POST['item_to_adjust'];
$quantity = $_POST['quantity'];
$quantity = preg_replace('#[^0-9]#i', '', $quantity); // filter everything but numbers
if ($quantity >= 100) { $quantity = 99; }
if ($quantity < 1) { $quantity = 1; }
if ($quantity == "") { $quantity = 1; }
$sqlquan = mysql_query("SELECT * FROM products WHERE id='$item_id' LIMIT 1");
while ($row = mysql_fetch_array($sqlquan)) {
$item_id= $row["id"];
$stock= $row["stock"];
}
if ($quantity > $stock)
{echo "much";
$quantity=$stock;}
$i = 0;
foreach ($_SESSION["cart_array"] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == "item_id" && $value == $item_to_adjust) {
// That item is in cart already so let's adjust its quantity using array_splice()
array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
} // close if condition
} // close while loop
} // close foreach loop
}
}
问题是购物车中有2件商品。第一个库存值为15,第二个库存值为23.如果我为第一个产品输入的数量大于15,则效果很好(将数量设置为15)。但是,如果我为第二个产品输入的值大于15但小于23,则将其与第一个产品的库存值进行比较,并再次重置为15.
答案 0 :(得分:0)
相当清理你的代码。希望这有效。
if(isset($_SESSION["cart_array"])) {
if(isset($_POST['item_to_adjust']) && !empty($_POST['item_to_adjust'])) {
$item_to_adjust = $_POST['item_to_adjust'];
$quantity = preg_replace('#[^0-9]#i', '', $_POST['quantity']); // filter everything but numbers
if ($quantity >= 100) $quantity = 99;
if (empty($quantity) || $quantity < 1) $quantity = 1;
$sqlquan = mysql_query("SELECT * FROM products WHERE id='$item_to_adjust' LIMIT 1"); // You previously used id='$item_id', I think you meant $item_to_adjust
// Since you have limited your query to only have 1 result, there is no need to use a while loop
// also note in your original code the while loop was closed prematurely.
$row = mysql_fetch_array($sqlquan);
// No need to create new variables when $row is accessible directly
if($quantity > $row["stock"]) {
echo "Requested Quantity exceeds currently available Stock.<br>";
$quantity = $row["stock"];
echo "Quantity set to maximum available stock of ".$row["stock"]."<br>";
}
foreach($_SESSION["cart_array"] as &$each_item) { // Referenced variable &$each_item so you do not have to use complicated array functions
if($each_item['item_id'] == $item_to_adjust) {
$each_item['quantity'] = $quantity;
break; // Terminates the foreach loop
}
} // close foreach loop
} else {
echo("Invalid Item ID");
}
}