Robert Coroianu
Robert Coroianu

Reputation: 426

Sum total rows of hours

I have a table with a column "worked hours" and i want to sum all rows like this:

    08:00 
    02:00 
    03:30
Total: 13:30

And this is my sql select code

$sql=mysql_query("SELECT * FROM sohy_works WHERE data_raport = '$data' AND codangajat = '$codangajat' ");

Upvotes: 0

Views: 782

Answers (2)

Danijel
Danijel

Reputation: 12689

Get sum of seconds from db and convert that to hours and minutes:

$q = "SELECT SUM(TIME_TO_SEC(worked_hours)) FROM sohy_works WHERE data_raport = '$data' AND codangajat = '$codangajat'";

$result = mysql_query( $q );
$sec = mysql_fetch_array($result);

$hours = floor( $sec[0]/3600 );
$minutes = str_pad( floor( $sec[0] % 3600/60 ), 2, '0', STR_PAD_LEFT );

echo $hours.':'.$minutes;

EDIT:

Hours and minutes can be calculated directly with SQL query like:

SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( `worked_hours` ) ) ) FROM ...

Upvotes: 2

Adem Öztaş
Adem Öztaş

Reputation: 21446

You can calculate like this,

SELECT SEC_TO_TIME( SUM( your_time_field ) ) FROM sohy_works WHERE .....

Upvotes: 3

Related Questions