php - 无法获取我的购物车中商品的总金额

标签 php mysql

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);

        }
    }
}

我试图获取我的购物车的总金额,但是当我回显 $subtotal 时,我得到的不是总金额,而是仅一件商品的价格

最佳答案

您可以通过不同的方式获得总金额。

一种方法可以像这样更改查询

$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);

    }
}

关于php - 无法获取我的购物车中商品的总金额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49312773/

相关文章:

java - MySQL-使用 INFILE 时将变量插入列中

mysql - 加快在 MySQL 中的插入

php - UTF8 与 php pear DB 包不起作用

mysql - 我应该在删除多行后重置表索引/优化吗?

php - 为 SMS 实现 GSM 调制解调器

php - 如何在 Zend Web 应用程序和 Zend JSON-RPC 服务器上使用相同的 "back end"代码?

javascript - 插入笑脸文字并播放图像

javascript - PHP/CSS/JS : whitening img background?

php - CodeIgniter PDO 驱动程序使用查询而不是准备?这不是更不安全吗?

mysql - SQL查询问题-当有最大数量时选择最短时间