0

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome. Just accept the answer when its ready to help others with the same question in the future. Good luck.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.