簡體   English   中英

從購物車中移除商品

[英]Removing item from shopping cart

我的網站上有購物車功能,我可以將商品添加到購物車中,我可以刪除除放入購物車的第一件商品之外的所有商品。 當我點擊“刪除”時,頁面會重新加載,但該項目仍在購物車中。 添加到購物車的任何其他項目都將被刪除,除了第一個。 這是我添加到購物車的代碼:

<?php
session_start();

if(isset($_GET['id']) & !empty($_GET['id'])){
    if(isset($_SESSION['cart']) & !empty($_SESSION['cart'])){

        $items = $_SESSION['cart'];
        $cartitems = explode(",", $items);
        if(in_array($_GET['id'], $cartitems)){
            header('location: cartIndex.php?status=incart');
        }else{
            $items .= "," . $_GET['id'];
            $_SESSION['cart'] = $items;
            header('location: cartIndex.php?status=success');

        }

    }else{
        $items = $_GET['id'];
        $_SESSION['cart'] = $items;
        header('location: cartIndex.php?status=success');
    }

}else{
    header('location: cartIndex.php?status=failed');
}
?>

這是我從購物車中刪除的代碼:

<?php 
session_start();
$items = $_SESSION['cart'];
$cartitems = explode(",", $items);
if(isset($_GET['remove']) & !empty($_GET['remove'])){
    $delitem = $_GET['remove'];
    unset($cartitems[$delitem]);
    $itemids = implode(",", $cartitems);
    $_SESSION['cart'] = $itemids;
}
header('location:cart.php')
?>

正如評論中的人們指出的那樣,有更好的方法來管理購物車。 通常,網站通過 MySQL 或 MongoDB 等服務將購物車存儲在其服務器數據庫中,然后在添加產品或從購物車中刪除產品時執行 XHR/AJAX 調用以更新它們。 但這既不在這里也不在那里,您需要修復特定的代碼,所以我會提供幫助。


您最有可能遇到的問題(我說最有可能是因為很難說它何時可能與 GET 值本身有關)是這一行:

unset($cartitems[$delitem]);

這樣做是在數組中搜索 item $delitem作為鍵,而不是搜索您想要做的值。 我的猜測是您要刪除的$delitem的 ID 等於 1,對嗎? Well 數組從 0 開始,這意味着它正在刪除第二個位置的項目,而不是 ID 匹配$delitem

我添加的代碼是:

if (($key = array_search($delitem, $cartitems)) !== false) {
    unset($cartitems[$key]);
}

array_search()返回它找到的元素的鍵,可用於使用unset()從原始數組中刪除該元素。 它會在失敗時返回FALSE ,但是它可以在成功時返回一個 false-y 值(例如,您的鍵可能是 0),這就是使用嚴格比較!==運算符的原因。

if()語句將檢查 array_search() 是否返回了一個值,並且只有在它返回時才會執行一個操作。

完成新代碼:

<?php 
    session_start();

    $items = $_SESSION['cart'];
    $cartitems = explode(",", $items);

    if(isset($_GET['remove']) & !empty($_GET['remove'])){

        $delitem = $_GET['remove'];

        if (($key = array_search($delitem, $cartitems)) !== false) {
            unset($cartitems[$key]);
        }

        $itemids = implode(",", $cartitems);
        $_SESSION['cart'] = $itemids;
    }

    header('location:cart.php');
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM