问:这是我的代码...
session_start();
$conn=mysqli_connect('localhost','root','...','ecom');
if(isset($_POST['add'])){
if(isset($_SESSION['SC'])){
$item_array_id=array_column($_SESSION['SC'],'item_id');
if(!in_array($_GET['id'],$item_array_id)){
$count=count($_SESSION['SC']);
$item_array=array(
'item_id'=> $_GET['id'],
'item_name'=>$_POST['name'],
'item_price'=>$_POST['pricehi'],
'item_quantity'=>$_POST['qty']
);
$_SESSION['SC'][$count]=$item_array;
}else{
echo'';
echo'';
}
}else{
$item_array=array(
'item_id'=> $_GET['id'],
'item_name'=>$_POST['name'],
'item_price'=>$_POST['pricehi'],
'item_quantity'=>$_POST['qty']
);
$_SESSION['SC'][0]=$item;
}
}
if(isset($_GET['action'])){
if($_GET['action']=='delete'){
foreach($_SESSION['SC'] as $keys =>$val){
if($val['item_id']==$_GET['id']){
unset($_SESSION['SC']['$keys']);
echo'';
echo'';
}
}
}
}
?>
Ecom$query='SELECT * FROM cart ';
$result=mysqli_query($conn,$query);
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_array($result)){
?>
<?php echo $row['title'];?>
<?php echo $row['price'];?>
>
>
}
}
?>
这是cart.php代码
session_start();
?>
CART
Name | Quantity | price | total | Action |
---|
if(!empty($_SESSION['SC'])){
$total=0;
foreach($_SESSION['SC'] as $key=>$val){
?>
<?php echo $val['item_name'];?><?php echo $val['item_quantity'];?><?php echo $val['item_price'];?><?php echo number_format ($val['item_quantity'] * $val['item_price'], 2);?> Remove$total= $total+($val['item_quantity'] * $val['item_price']);
}
?>
total<?php echo number_format($total,2);?>}
?>
```and the output is persisted with product1
Name Quantity price total Action
a.apple 1 100 100.00 Remove
total 100.00
答:尝试var_dump($ _ SESSION ['SC']); 检查会话变量中真正包含的内容。
问题可能出在您如何将商品添加到购物车中。在显示的第一个代码中将商品添加到购物车的语句之后,执行var_dump($ _ SESSION ['SC']);。并查看是否总是数组中只有一个元素。