当我更新会话数组中的值时,它们将被清除


Values in session array are being cleared when I update them

我正在构建一个购物车,遇到了一个我无法弄清楚的问题。

当我将更新的数量保存在购物车中时,它会清除存储在$_SESSION['cart']中的值,但我更新的值除外。

<?php
session_start();
$new = $_GET['new']; //new product entry into cart
if($new){
    if(!isset($_SESSION['cart'])){
        $_SESSION['cart'] = array();
        $_SESSION['items'] = 0;
        $_SESSION['total_price'] = '0.00';
    }
    if(isset($_SESSION['cart'][$new])){
        $_SESSION['cart'][$new]++;
    }else{
        $_SESSION['cart'][$new] = 1;
    }
    //$_SESSION['total_price'] = calculate_price($_SESSION['cart']);
    //$_SESSION['items'] = calculate_items($_SESSION['cart']);
};
if(isset($_POST['save'])){                                -----
    foreach($_SESSION['cart'] as $newId=>$qty){                |
        if($_POST[$newId] == '0'){                             | I think the
            unset($_SESSION['cart'][$newId]);                  | problem is
        } else {                                               | here?
            $_SESSION['cart'][$newId] = $_POST[$newId];        | 
        }                                                 -----
    }
    //run price and item functions
};
if(($_SESSION['cart']) && (array_count_values($_SESSION['cart']))){
    $cart = $_SESSION['cart'];
    foreach($cart as $newProd=>$qty) {
        require 'connect.inc.php';
        $query = "SELECT `product_id`, `new_id`, `name`, `price`, `image` FROM `products` WHERE `new_id` = '$newProd'";
        if ($query_run = mysql_query($query)) {
            while ($query_row = mysql_fetch_assoc($query_run)) {
                $product = $query_row['name'];
                $price = $query_row['price'];
                $image = $query_row['image'];
                $productId = $query_row['product_id'];
                $newId = $query_row['new_id'];
$tile = <<<TILE
    <article class="itemCart">
        <h1>$product</h1>
        <img src="$image">    
        <p>$price GBP</p>
        <form action="shopping-cart.php" method="post"><label for="$newId">Quantity </label>
        <input id="cartQty" type="number" value="$qty" max="30" min="0" name="$newId"></br>
        <input type="submit" name="save" value="Update"></form>
    </article>
TILE;
    echo $tile;
            }
        } else {
            echo mysql_error();
        }
    }
}else{
    echo '<h2>No items in your shopping cart</h2>';
};

我已经想通了!我正在与购物车中的每件商品回响<form>标签。

$tile = <<<TILE
<article class="itemCart">
    <h1>$product</h1>
    <img src="$image">    
    <p>$price GBP</p>
    <form action="shopping-cart.php" method="post"><label for="$newId">Quantity </label>
    <input id="cartQty" type="number" value="$qty" max="30" min="0" name="$newId"></br>
    <input type="submit" name="save" value="Update"></form>
</article>
TILE;
echo $tile;

我已经将整个脚本包含在<form action="shopping-cart.php" method="post"></form>中。我将使用 ajax 改进这个购物车,以便我可以更新购物车而无需每次刷新页面......当我有时间学习它时。

希望这可以帮助任何犯了与我相同的错误的人。