更新会话变量不工作的PHP

时间:2017-10-04 05:33:04

标签: php session

我现在正在购物车中工作,其中所有产品都保存在会话变量中。因此,如果购物车中存在相同的产品,则只会增加数量。但是当我回显变量时看起来像是工作但是当我打印会话变量时它保持不变。这是我的代码

<?php
require_once("inc/init.php");

$product_id = htmlentities($_POST['product_id'], ENT_QUOTES);
$quantiy_added = htmlentities($_POST['quantiy_added'], ENT_QUOTES);
$op = htmlentities($_POST['op'], ENT_QUOTES);

$Cart = new Cart();

//var_dump($Cart);

global $mysqli;

if ($op == "add-item") {
    if (isset($_SESSION['careat_cart'])) {              //if same item exists
        foreach ($_SESSION['careat_cart'] as $key => $value) {
            if ($product_id == $value['id']) {
                $value['quantity'] += $quantiy_added;
                echo $value['quantity'];
            } else echo "new item";

        }

    }
} 

2 个答案:

答案 0 :(得分:2)

<?php
session_start();
require_once("inc/init.php");

$product_id = htmlentities($_POST['product_id'], ENT_QUOTES);
$quantiy_added = htmlentities($_POST['quantiy_added'], ENT_QUOTES);
$op = htmlentities($_POST['op'], ENT_QUOTES);

$Cart = new Cart();

//var_dump($Cart);

global $mysqli;

if ($op == "add-item") {
    if (isset($_SESSION['careat_cart'])) {              //if same item exists
        foreach ($_SESSION['careat_cart'] as $key => $value) {
            if ($product_id == $value['id']) {

                $value['quantity'] += $quantiy_added;
                echo $value['quantity'];
            } else echo "new item";

        }

    }
} 

答案 1 :(得分:0)

我找到了解决方案。这将是 $ _SESSION [&#39; careat_cart&#39;] [$ key] [&#39;数量&#39;] + = $ quantiy_added; 而不是 $ value [&#39;数量&#39;] + = $ quanty_added; 现在任何人都可以告诉我这两行之间的差异。提前致谢