Jamilah Jamilah - 5 days ago 6
PHP Question

How to calculate rows in query PHP MySQL?

I have to 2 rows of query of sum_hour(double type) in database

1st row = sum_hour = 2.75

2nd row = sum_hour = 3.00

It belongs inside 2(two) groups which is type_move = 'P' and (start date >= 2016-11-11 AND end_date <= 2016-11-15) group. The code as below :

<?php
$sql = "SELECT sum_hour,
SUM(sum_hour)
FROM table
WHERE type_move = 'P' AND user_id='username' AND (start_date >= '2016-11-11' AND end_date <= '2016-11-15')
GROUP BY sum_hour ";

$result = mysqli_query($connect, $sql);
if($result && mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$hour = $row['sum_hour'];
echo " Hours = " .$hour. "<br/>";
print_r($row);
}

echo "Total hours = " .$hour. "<br/>";

mysqli_free_result($result);
}
else
{
echo mysqli_error($connect);
}
?>


And the output as below :

Hours = 2.75

Hours = 3.00

Total hours = ?

My question is , how to calculate 2 rows (Hours) above ? I tried to run sql statement in phpmyadmin. It work and i can see the value sum up into = 5.75 but i don't know how to echo the total in browser

Thanks.

Answer

Just update your loop with this:

$totalHours = 0;

while($row = mysqli_fetch_assoc($result))
    {   
        $hour = $row['sum_hour'];

        $totalHours += $hour;

        echo " Hours = " .$hour. "<br/>";
        print_r($row);
    }

echo "Total hours = " .$totalHours. "<br/>";

You need to store the first value in a variable then add the second one to the first value. Just make sure that the value can be read outside the loop.

Comments