不能得到一个购物车的总计PHP/MySQL
我试图抓住我的购物车的总计,但我似乎无法让它工作,我想知道如果它的方式我已经接近我的代码,我有使用foreach循环从会话数组中获取id,然后循环遍历结果,但是当我尝试执行SUM查询时,答案仅输出单个价格作为数组,以便将它们添加到一起。将价格存储在二维数组中会更好吗?不能得到一个购物车的总计PHP/MySQL
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>£'.$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>£'.$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>';
}
?>
?>
谢谢你的工作,感谢上帝,像你这样的人:) – Greyhamne 2012-02-16 08:35:53
'SELECT SUM(price) as total_cost FROM product_item where id="'.$value.'"'
如果你的ID是唯一的,它永远把 '价格' 值。 此外,你的总和是在foreach。 如果你想要总价格,我建议你保持价格值在PHP变量和总结在foreach,那么你只需要在最后显示这个变量。
并且不推荐使用“select *”,您应该放置要检索的字段。
感谢您的帮助,是的,我会开始删除*我的查询,因为我听到那懒惰 – Greyhamne 2012-02-16 08:36:32
您可以通过遍历购物车中的物品来计算PHP中的总和。如果你真的想用SQL来做,你必须在foreach
循环之外完成,因为它一次只能给你一个项目的价格。
使用implode()
您可以连接在车中的所有项目ID到一个列表中查询中使用:
$y = mysql_query("SELECT SUM(price) AS total_cost FROM product_item WHERE id IN (" . implode(", ", $_SESSION['cart']) . ")";
你尝试直接在SQL查询?它可能是查询 – Joseph 2012-02-16 08:29:44