PHP MYSQL显示来自不同ID的表数据

时间:2019-05-17 03:18:52

标签: php mysql

mysql tables

如何输出所选product_id的product_price SUM?

当前输出为“ 1245”。它似乎正在工作,但是将“ 124”放在“ 5”前面。我想要的结果是“ 5”。

查看图片以获取更多详细信息。

$query = "SELECT * FROM product_list WHERE school_subject_product_id = '1'"; //<---- There are 4 products under this id

$result = $mysqli->query($query);
    while($row = $result->fetch_assoc()){
        $product_id = $row["product_id"];
        $sql = "SELECT SUM(product_price) as total FROM products WHERE product_id = $product_id";
        $query = $mysqli->query($sql);
        $row = $query->fetch_assoc();
        $sum += $row['total'];
        echo $sum;
    }// end of while

1 个答案:

答案 0 :(得分:0)

$sum变量放在循环之外,以免重复数据的重复发生