1

我有一个 PHP 代码可以将商品添加到购物车,如下所示:

if (is_array($_SESSION['cart']['itemId']))
        {
    $max=count($_SESSION['cart']);
    $_SESSION['cart'][$max]['itemId']=$pid;
    $_SESSION['cart']['itemId']['qty']= $_SESSION['cart']['itemId']['qty'] + $q;
    $max=count($_SESSION['cart']);
        }
else
        {
    $_SESSION['cart']=array();
    $_SESSION['cart'][0]['itemId']=$pid;
    $_SESSION['cart']['itemId']['qty'] = $q;
    $max=count($_SESSION['cart']);
        }

然后我尝试显示添加到购物车的项目,如下所示:

if(is_array($_SESSION['cart']))
        {
       $max=count($_SESSION['cart']);
       for($i=0;$i<$max;$i++)
                   {
                $pid=$_SESSION['cart'][$i]['itemId'];
        $q=$_SESSION['cart'][$i]['qty'];
        if($q==0) continue;
    $query2 = $con -> prepare("SELECT * FROM item_descr WHERE id_item = :idItem");
    $query2-> bindValue (':idItem',$pid);

但是,我的任何物品都没有加载。你知道我做错了什么吗?

4

2 回答 2

1

您的会话对象“购物车”具有不同的元素


$_SESSION['cart'][$max]['itemId']​​=$pid;
$_SESSION['cart']['itemId']​​['qty']= $_SESSION['cart']['itemId']​​['qty'] + $q;
在上面两行 $max 和 'itemId' 是不同的,所以你不能像数组一样访问它们

于 2013-02-21T16:10:31.813 回答
0

您需要在 PHP 文件的开头初始化会话:

<?php

session_start();

见手册

于 2013-02-21T16:02:12.503 回答