购物车“删除”不再工作

时间:2014-02-23 01:02:22

标签: php

我设法让我的所有产品都添加了每个项目的选项,每个项目都出现在单独的行中并正确提交。

see my previous question

现在,当我尝试删除设置了选项的项目时,它不会删除任何内容。我的添加代码是这样的:

switch($action) {
    case "add": 

       $_SESSION['options'.$productID] = $optionsSelected;

       $key = $productID . ":" . base64_encode(serialize($optionsSelected));

       $_SESSION['cart'][$key]++;

       header('location: /shop/cart');

    break;

然后我的删除案例就像这样:

        case "remove": 

            $key = $_GET['key'];
            $product = explode(':', $key);
            $productId = $product[0];
            $optionsSelected = unserialize(base64_decode($product[1]));

            $_SESSION['cart'][$key]--;

            if($_SESSION['cart'][$key] == 0)
            {
                unset($_SESSION['cart'][$key]);
            }

            header('location: /shop/cart');

        break;

每个选项都会使用如下所示的URL触发删除功能:

<a href="/shop/actions/cart_actions.php?action=remove&id=<?php echo $item['id']; ?>&key=<?php echo $key; ?>" class="btn btn-danger">

现在,如果我删除没有设置选项的产品,它就会删除。如果产品有选项,则不会删除。

更新

当我<?php var_dump($_SESSION['cart']); ?>时,我得到以下内容:

array(2) { ["433771:YToyOntpOjA7czo1OiJSdW50cyI7aToxO3M6NzoiU2l4bGV0cyI7fQ=="]=> int(1) ["433771:YToyOntpOjA7czoyMToiU3dlZGlzaCBGaXNoIEFzc29ydGVkIjtpOjE7czozMToiQmVhcnkgQmx1ZSBSYXNiZXJyeSBHdW1taSBCZWFycyI7fQ=="]=> int(1) }

1 个答案:

答案 0 :(得分:0)

抱歉,我几天没有检查过该网站。我测试了上面的代码,相关部分按预期工作,但我确实看到了一些问题。您是否尝试过var_dump($_SESSION)来确定事情是否正确设置?

尝试此操作,它会假定$productID$optionsSelected根据需要在上面定义,并且会话已经启动。经过测试的工作。

<?php

switch ($action) {
    case "add":

        $key = $productID . ":" . base64_encode(serialize($optionsSelected));

        // ensure the cart array exists
        if (!isset($_SESSION['cart'])) {
            $_SESSION['cart'] = array();
        }

        // create entry, or add to it
        if (!isset($_SESSION['cart'][$key])) {
            $_SESSION['cart'][$key] = 1;
        } else {
            $_SESSION['cart'][$key]++;
        }

        header('location: /shop/cart');
        // always exit after sending a location header, or the rest of the script will continue to execute first
        exit;
        break;

    case "remove":

        $key = $_GET['key'];

        if (isset($_SESSION['cart'], $_SESSION['cart'][$key])) {
            if ($_SESSION['cart'][$key] > 1) {
                $_SESSION['cart'][$key]--;
            } else {
                unset($_SESSION['cart'][$key]);
            }
        }

        header('location: /shop/cart');
        exit;
        break;
}