gpt4 book ai didi

php - PHP/MySQL 无法获取购物车总计

转载 作者:行者123 更新时间:2023-11-29 08:58:24 25 4
gpt4 key购买 nike

我试图获取我的购物车的总数,但我似乎无法让它工作,我想知道这是否是我处理代码的方式,我使用了 foreach 循环从 session 中获取 id数组,然后循环遍历结果,但是当我尝试进行 SUM 查询时,答案只是将各个价格输出为数组,而不是将它们加在一起。将价格存储在二维数组中会更好吗?

if(!isset($_SESSION['cart'])){//
$_SESSION['cart']=array();//creating session array to store items id
}
<?php
echo'<table class="table">';
echo'<tr>';
echo'<th>Item</th>';
echo'<th>Code</th>';
echo'<th>Description</th>';
echo'<th>Cost(GBP)</th>';
echo'<th>Remove</th>';
echo'</tr>';

foreach ($_SESSION['cart'] as $value){
$z = mysql_query('SELECT * FROM product_item where id="'.$value.'"');
while($row = mysql_fetch_array($z)){
echo'<tr>';
echo'<td><img src="images/'.$row['path'].'.jpg" alt="'.$row['alt'].'" width="65" height="65"/></td>';
echo'<td>'.$row['code'].'</td>';
echo'<td>'.$row['description'].'</td>';
echo'<td><p>&pound;'.$row['price'].'</p></td>';
echo'<td><p><a title="remove from shopping cart" href="cart.php?remove='.$value.'">X</a></p></td>';
echo'</tr>';
}


// this is where i want to get total cost
$y = mysql_query('SELECT SUM(price) as total_cost FROM product_item where id="'.$value.'"');
while($row = mysql_fetch_array($y)){
echo $row['total_cost'];
}

}

echo'<tr>';
echo'<td></td>';
echo'<td></td>';
echo'<td></td>';
echo'<td><p>Total</p></td>';
echo'<td></td>';
echo'</tr>';
echo'</table>';
}
?>
?>

最佳答案

为什么不是外部变量?

if(!isset($_SESSION['cart'])){//
$_SESSION['cart']=array();//creating session array to store items id

$cartTotal = 0; //This is where you store the total
}
<?php
echo'<table class="table">';
echo'<tr>';
echo'<th>Item</th>';
echo'<th>Code</th>';
echo'<th>Description</th>';
echo'<th>Cost(GBP)</th>';
echo'<th>Remove</th>';
echo'</tr>';

foreach ($_SESSION['cart'] as $value){
$z = mysql_query('SELECT * FROM product_item where id="'.$value.'"');
while($row = mysql_fetch_array($z)){
$cartTotal += $row['price'];
echo'<tr>';
echo'<td><img src="images/'.$row['path'].'.jpg" alt="'.$row['alt'].'" width="65" height="65"/></td>';
echo'<td>'.$row['code'].'</td>';
echo'<td>'.$row['description'].'</td>';
echo'<td><p>&pound;'.$row['price'].'</p></td>';
echo'<td><p><a title="remove from shopping cart" href="cart.php?remove='.$value.'">X</a></p></td>';
echo'</tr>';
}
}
echo $cartTotal; //after running through all the items, you can show the total

echo'<tr>';
echo'<td></td>';
echo'<td></td>';
echo'<td></td>';
echo'<td><p>Total</p></td>';
echo'<td></td>';
echo'</tr>';
echo'</table>';
}
?>
?>

关于php - PHP/MySQL 无法获取购物车总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9307787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com