簡體   English   中英

PHP從購物車刪除商品

[英]PHP delete item from Shopping cart

我創建了一個非常簡單的購物車,僅向其中添加了項目s並從中刪除了項目,現在也清空了購物車。我知道我的代碼中存在很多問題,但我也正在嘗試對其進行修復

首先看我的代碼

if (isset($_SESSION['cart'])) {
    foreach ($_SESSION['cart'] as $c) {
        echo $c['name'] . '<br />';
        echo $c['price'] . '<br />';
        echo '<a href="?pid=17&rc=' . $c['code'] . '">Remove item</a><br />';
    }
}


if (isset($_POST['buy'])) {
    //header("Location:?pid=18&pl=" . $pl);
    if (isset($_POST['buy'])) {
        $getData = $db->prepare('SELECT * FROM plans WHERE id=?');
        $getData->bind_param('i', $pl);
        if ($getData->execute()) {
            $res = $getData->get_result();
            if (($pn = $res->fetch_object()) !== null) {
                $proCode = rand(1, 100);

                $item['name'] = $pn->plan_name;
                $item['price'] = $pn->price_dollar;
                $item['code'] = $proCode;
                $_SESSION['cart'][] = $item;
            }
        }
    }
}

echo '<a href="?pid=17&ac=empty">Empty Cart</a>';

if (isset($_GET['rc']) && isset($_SESSION['cart'])) {
    $rem = $_GET['rc'];
    $ses = $_SESSION['cart'];

    foreach ($_SESSION['cart'] as $cartItem) {
        if ($cartItem["code"] == $rem) {
            unset($ses[$rem]);
        }
    }

    /*if (($key = array_search($rem, $ses)) !== false) {
        unset($ses[$key]);
    }*/
    var_dump($ses);
}

if (isset($_GET['ac']) == 'empty' && isset($_SESSION['cart'])) {
    unset($_SESSION['cart']);
}

目前,添加新產品對我來說還可以,但是當我試圖從插入符中刪除一個項目時,問題就來了,它返回並注意到似乎發生了,而該項目仍在購物車中

您正在設置$ses變量而不是$_SESSION ...

請看一下更新后的代碼,您甚至不需要使用forloop ,就可以像下面那樣unset變量

 if (isset($_GET['rc']) && isset($_SESSION['cart'])) 
 {
    $rem = $_GET['rc'];    
    if(isset($_SESSION['cart'][$rem]))
    {
       unset($_SESSION['cart'][$rem]);
    }
}

讓我知道這是否對您有幫助

編輯

請更新您的購買產品功能至以下。.您正在使用auto increament key for array ..它應該是主鍵(此處是您的產品代碼)

if (isset($_POST['buy'])) {
    //header("Location:?pid=18&pl=" . $pl);
    if (isset($_POST['buy'])) {
        $getData = $db->prepare('SELECT * FROM plans WHERE id=?');
        $getData->bind_param('i', $pl);
        if ($getData->execute()) {
            $res = $getData->get_result();
            if (($pn = $res->fetch_object()) !== null) {
                $proCode = rand(1, 100);

                $item['name'] = $pn->plan_name;
                $item['price'] = $pn->price_dollar;
                $item['code'] = $proCode;
                $_SESSION['cart'][$proCode] = $item;
            }
        }
    }
}

嘗試將刪除周期更改為此:

foreach ($_SESSION['cart'] as $key=>$cartItem) {
        if ($cartItem["code"] == $rem) {
            unset($_SESSION['cart'][$key]);
        }

暫無
暫無

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

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