[英]php update quantity on cart page
我想更新購物車中物品的數量
這些是動作:
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM menu WHERE item_code='" . $_GET["code"] . "'");
$itemArray = array($productByCode[0]["item_code"]=>array('name'=>$productByCode[0]["item_name"], 'code'=>$productByCode[0]["item_code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["item_price"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["item_code"],$_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["item_code"] == $k)
$_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
break;
case "remove":
if(!empty($_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($_GET["code"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
break;
case "empty":
unset($_SESSION["cart_item"]);
break;
}
}
這是購物車代碼:
<?php
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td><strong><?php echo $item["name"]; ?></strong></td>
<td><?php echo $item["quantity"]; ?></td>
<td><?php echo "₹".$item["price"]; ?></td>
<td><a id="remove" href="index.php?action=remove&code=<?php echo $item["code"]; ?>"><span class="fa fa-times fa-lg" style="color:red;"></span></a></td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
}
?>
我需要類似單擊更新按鈕時的內容,以便它可以獲取值並更新特定產品數量的會話數組。請幫助我...
這是一個非常基本的示例,但是您應該為每個動作創建一個函數,以便更輕松地移植購物車。 另外,我不確定為什么在switch
有$_GET
而在case()
有$_POST
:
function AddToCart($default = 1)
{
// Set a default quantity (1). Check that the value is set and is number
// Not sure why you are using a get for the code but not for these
// attributes. Should it not be $_GET['quantity']??
$qty = (isset($_POST['quantity']) && is_numeric($_POST['quantity']))? $_POST['quantity']:$default;
// Check that there is a valid numeric itemcode
$item = (isset($_POST['item_code']) && is_numeric($_POST['item_code']))? $_POST['item_code']:false;
// If false, stop
if(!$item)
return;
// Do your product query
$productByCode = $db_handle->runQuery("SELECT * FROM menu WHERE item_code='" . $_GET["code"] . "'");
// Assign the item code
$itmcd = $_GET["code"];
$itemArray['code'] = $itmcd;
$itemArray['name'] = $productByCode[0]["item_name"];
$itemArray['price'] = $productByCode[0]["item_price"];
$itemArray['quantity'] = (isset($_SESSION["cart_item"][$itmcd]))? $_SESSION["cart_item"][$itmcd]['quantity']+$qty : $qty;
$_SESSION["cart_item"][$itmcd] = $itemArray;
}
使用方法:
if(isset($_GET["action"]) && $_GET["action"] == 'add'))
AddToCart();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.