-2

すべての作業を行うために cart.php というファイルを使用する Web サイトにショッピング カートをセットアップしました。「追加」機能は完全に機能し、カートを空にすることもできますが、単一のアイテムを削除することはできません

削除リンクは次のようになります。

<a href='cart.php?action=delete&id=$cartId'>delete</a> 

次のようなリンクが作成されます。cart.php?action=delete&id=1

ファイル cart.php は次のとおりです。

<?php
require_once('Connections/ships.php');
// Include functions
require_once('inc/functions.inc.php');
// Start the session
session_start();
// Process actions
$cart = $_SESSION['cart'];
$action = $_GET['action'];

$items = explode(',',$cart);


    if (count($items) > 5) 
    {
    header("Location: shipinfo_full.php") ;
    }
    else 
    {
    switch ($action) 
        {
        case 'add':
        if ($cart) 
            {
            $cart .= ','.$_GET['ship_id'];
            } 
            else 
            {
            $cart = $_GET['ship_id'];
            }
            header("Location: info_added.php?ship_id=" .  $_GET['ship_id']) ;
            break;
            case 'delete':
            if ($cart) 
            {
            $items = explode(',',$cart);
            $newcart = '';
            foreach ($items as $item) 
                {
                if ($_GET['ship_id'] != $item) 
                    {
                    if ($newcart != '') 
                        {
                        $newcart .= ','.$item;
                        } 
                        else 
                        {
                        $newcart = $item;
                        }
                    }
                }
                $cart = $newcart;

            }
            header("Location: info.php?ship_id=" .  $_GET['ship_id']) ;
            break;
            $cart = $newcart;
            break;
        }
        $_SESSION['cart'] = $cart;

    }
?>

単一のアイテムを削除する方法はありますか?

4

2 に答える 2

0

これをチェックしてください:

case 'delete':
    if ($cart) 
    {
        $items = explode(',',$cart);
        $newcart = array();
        foreach ($items as $item) 
        {
            if ($_GET['ship_id'] != $item) 
            {
                $newcart[] = $item;

            }
        }
        $_SESSION['cart'] = implode(',', $newcart);

    }
    header("Location: info.php?ship_id=" .  $_GET['ship_id']) ;
break;

newcartを除くすべての項目で配列を埋め$_GET['ship_id']ます。もう1つ、リダイレクトする前にセッションを埋めてください。

于 2013-07-27T21:17:52.557 に答える
0

次のように、セッション内の配列にアイテムを格納することで、より良い方法で書くことができます

$_SESSION['cart'] = array(); // cart is initially empty

カートにアイテムを追加中

$_SESSION['cart'][] = array('name' => 'some name', 'price' => 100);

カートからアイテムを削除する

unset($_SESSION['cart'][22]); // assuming that 22 is the item ID

出品商品

$cart = $_SESSION['cart'];
forearch($cart as $item){
    echo $item['name']; }
于 2013-07-27T20:55:40.707 に答える