简体   繁体   中英

Multiply column values from multiple rows and then add

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

EDIT:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM