将多行的列值相乘,然后相加 [英] Multiply column values from multiple rows and then add

查看:40
本文介绍了将多行的列值相乘,然后相加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从数据库中获取价格和销售量,然后将它们相乘以获得每个的输出,然后将它们全部相加.我想我可以使用 foreach 循环,但我不确定变量是否会在每次经过时保留它的值.这是我迄今为止尝试过的:

I need to get the price and amount sold from a database, and then multiply them together to get an output for each one, and then add them all together. I think I could use a foreach loop, but I'm not sure if the variable would retain it's value for each time it goes through. This is what I've tried so far:

    $query = "SELECT * FROM `inv`";
    $data = mysqli_query($dbc, $query);
    while($row = mysqli_fetch_array($data)){
        if(isset($fin2)){
            $fin = $fin2;
        } else {
            $price = str_replace('$', '', $row['price']);
            $fin2 = ($row['sold'] * $price + $fin);                 
        }
        if(isset($fin)){
        $fin = ($fin + $fin2);
        echo $fin;
        } 

如您所见,我有点困惑,我们将不胜感激.

As you can see, I'm kind of confused, and any help would be appreciated.

推荐答案

为什么不在数据库中进行计算?

Why not do the calculation in the database?

SELECT SUM(price * sold) as total
FROM `inv`;

SELECT SUM((replace(price, '$', '') + 0) * sold) as total
FROM `inv`;

这篇关于将多行的列值相乘,然后相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆