[英]Incrementing quantity of items in cart when item is added again
如果該商品已經在購物車中,則當我向購物車中添加特定商品時,我需要更新其數量。 現在,添加了重復項目,而不是更新數量。 任何人都可以幫忙! 下面的代碼。
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM medicine WHERE med_id='" . $_GET["med_id"] . "'");
$itemArray = array(
$productByCode[0]["med_id"]=>array(
'name'=>$productByCode[0]["med_name"],
'med_id'=>$productByCode[0]["med_id"],
'image'=>$productByCode[0]["Image"],
'quantity'=>$_POST["quantity"],
'price'=>$productByCode[0]["unit_cost"]
)
);
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["med_id"],$_SESSION["cart_item"])){
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["med_id"] == $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["med_id"] == $_SESSION["cart_item"][$k]['med_id'])
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
break;
為了解決增加的問題,我可能會看看通過使用函數來重做邏輯是否會有所幫助。 我也要清理一下。 將功能存儲在單獨的頁面上,並在使用之前包括它們:
function getMedsById($id,$db)
{
if(!is_numeric($id))
return false;
$productByCode = $db->runQuery("SELECT * FROM medicine WHERE med_id='" . $id . "'");
$product = (!empty($productByCode[0]["med_id"]))? $productByCode[0] : false;
if(empty($product))
return false;
return array(
'name'=>$product["med_name"],
'med_id'=>$product["med_id"],
'image'=>$product["Image"],
'price'=>$product["unit_cost"]
);
}
function addToCart($array,$id,$qty)
{
$array['quantity'] = $qty;
# Save item to cart
$_SESSION["cart_item"][$id] = $array;
}
返修開關:
case "add":
if(!empty($_POST["quantity"])) {
# Just do a basic ternary to avoid warnings
$id = (!empty($_GET["med_id"]))? $_GET["med_id"] : false;
# Check input not manipulated
$qty = (!empty($_POST['quantity']) && is_numeric($_POST['quantity']))? $_POST['quantity'] : 1;
# Use the function to get the item from db
$prod = getMedsById($id,$db_handle);
# Stop if return is empty (user may be trying to manipulate cart)
if(empty($prod))
break;
# Same as yours
if(!empty($_SESSION["cart_item"])) {
# Check if this product is already set
if(isset($_SESSION["cart_item"][$id])){
# If already set, just add the qty to existing
$_SESSION['cart_item'][$id]['quantity'] += $qty;
# Stop the add process here
break;
}
}
# Just add to cart here, it won't get here if already in cart
addToCart($prod,$id,$qty);
}
break;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.