简体   繁体   English

更新会话变量不起作用php

[英]Updating session variable not working php

im now working in a cart where all products saved in a session variable.我现在在一个购物车中工作,所有产品都保存在一个会话变量中。 So if the same product exists in the cart it will just increase the quantity.因此,如果购物车中存在相同的产品,它只会增加数量。 But it looks like working when i echo out the variable but when i print the session variable it remain same.但是当我回显变量时它看起来像工作但是当我打印会话变量时它保持不变。 here is my code这是我的代码

<?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";

        }

    }
} 
<?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";

        }

    }
} 

I found the solution.我找到了解决方案。 It would be这将是

$_SESSION['careat_cart'][$key]['quantity']+= $quantiy_added;

Instead of而不是

$value['quantity'] += $quantiy_added;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM