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
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 to share
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 to share