Find the sum of a value from an array

I have a cart table and want to calculate the amount of value wherever I have a status = 1

id  cost   status
1   10     1
2   10     1
2   10     1
2   10     2

      

the code i tried is

$sql01 = "SELECT * FROM cart where status='1' ";

$result01 = mysqli_query($con, $sql01);
if (mysqli_num_rows($result01) > 0) 
    {
        while($row = mysqli_fetch_assoc($result01)) 
            {
                $price = array_sum($row);
                echo "sum of cod:"; echo $price;
                echo "<br>";
            }
    }

      

the result i get is

10
10
10

      

The result that should be

30

      

+3


source to share


5 answers


One way to do this is to calculate the sum in SQL, just like the other answer. If you want to do this in PHP, you can add a column cost

to a variable:



$total_cost = 0;
while ($row = mysqli_fetch_assoc($result01)) {
    $total_cost += $row['cost'];
}
echo "Result: $total_cost";

      

+4


source


You calculate the sum for each row. You should try this instead:

$sql01 = "SELECT * FROM cart where status='1'";

$result01 = mysqli_query($con, $sql01);
$cost_array = array();
if (mysqli_num_rows($result01) > 0) 
    {
        while($row = mysqli_fetch_assoc($result01)) 
            $cost_array[] = $row['cost'];
    }
echo "Result: ".array_sum($cost_array);

      

Or (better!) Optimize your MySQL query this way:



SELECT sum(cost) finalprice FROM cart where status='1' GROUP BY status

      

You can now access your amount using $row['finalprice']

.

+1


source


This is the request for you:

SELECT sum(cost) as price FROM cart WHERE status='1' GROUP BY status

      

PHP code:

$sql01 = 'SELECT sum(cost) as price FROM cart WHERE status='1' GROUP BY status'
$result01 = mysqli_query($con, $sql01);
if (mysqli_num_rows($result01) > 0) 
    {
        while($row = mysqli_fetch_assoc($result01)) 
            {
                echo 'sum of cod:' . $row['price'] . '<br>';
            }
    }

      

More about GROUP BY at:

https://dev.mysql.com/doc/refman/5.0/en/group-by-functions-and-modifiers.html

+1


source


It's easier than your code: in SQL, you should use

"Select sum(cost) from cart where status = '1';"

      

+1


source


Use this:

SELECT sum(cost) FROM cart group by status having status='1'

      

0


source







All Articles