if (isset($_SESSION['cart'])) {
foreach($_SESSION['cart'] as $key => $value) {
$sql = "SELECT product_name, image, price, sum(price) AS subtotal FROM
items WHERE id = '$key'
";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$item = mysqli_fetch_assoc($result);
extract($item);
}
}
}
我试图得到我的购物车的总和,但当我回应$小计时,我得到的不是总和而是只有一个项目的价格
答案 0 :(得分:0)
您可以通过不同方式获得总和。
一种方法是像这样更改查询
$ids = array();
if (isset($_SESSION['cart'])) {
foreach($_SESSION['cart'] as $key => $value) {
$ids[] = $key; //get all the ids
}
$ids = implode(',', $ids); //make the ids array a string like this 1,2,3...
$sql = "SELECT product_name, image, price, sum(price) AS subtotal FROM
items WHERE id IN ($ids)";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$item = mysqli_fetch_assoc($result);
extract($item);
}
}
答案 1 :(得分:0)
尝试此查询:
SELECT A.*, SUM(subtotal) AS grandTotal
FROM (SELECT product_name, image, price, COUNT(*) quantity, price * COUNT(*) AS subtotal
FROM items
WHERE id IN ($ids)
GROUP BY product_name, image, price) A;