Calculating total hours out of database

2019-08-10 20:29发布

I have a Log in PHP which shows all the things I've done.

the construction is like:

Date -- Things done -- Hours

I figured how to show all the info in a table. But I want to have a total hours in the bottom which calculated all the hours of the database.

I'm adding every day a new log (what I've done that day). But I wanna know how I can do this. I've been searching for a while now, without success..

I hope anyone can help me.

Thanks in advance.

This is how I display my code(short version):

 <tr>
        <td class="date"><?php echo $row['Date'] ?></td>
        <td><?php echo $row['Detail'] ?></td>
        <td><?php echo $row['Hours'] ?></td>
    </tr>

So for clarification:

I make a new td which echo's the total hours by adding all the hours.

So if my hours are 8 + 8 + 8 + 8 + 4 + 5 in the hours table it will be shown as:

Total hours: 41 hours

标签: php mysqli
1条回答
Emotional °昔
2楼-- · 2019-08-10 20:59

To display the total sum of hours, you do this:

$db = new mysqli( DB_HOST, DB_USER, DB_PASS, DB_DATABASE );
$sql = 'SELECT SUM( `Hours` ) AS `total` FROM `table_name`';
$res = $db->query( $sql ) or die( 'MySQL error ' . $db->error );
$row = $res->fetch_assoc();
echo 'Total: ' . $row['total'];

If date is of typ datetime/date/timestamp you can get the total for every day like this (If the date is of type date, you do not need DATE(date)):

$sql = 'SELECT DATE(`date`) AS `day`, SUM(`Hours`) as `total` '
     . 'FROM `table_name` GROUP BY DATE(`date`) ORDER BY `date`';
$res = $db->query( $sql ) or die( 'MySQL error ' . $db->error );
while( $row = $res->fetch_assoc() )
    echo $row['day'] . ' has ' . $row['total'] . ' hours' . PHP_EOL;

If date is of typ int or PHP timestamp you can get the total for every day like this:

$sql = 'SELECT DATE( FROM_UNIXTIME(`date`) ) AS `day`, SUM(`Hours`) as `total` '
     . 'FROM `table_name` GROUP BY DATE(FROM_UNIXTIME(`date`)) ORDER BY `date`';
$res = $db->query( $sql ) or die( 'MySQL error ' . $db->error );
while( $row = $res->fetch_assoc() )
    echo $row['day'] . ' has ' . $row['total'] . ' hours' . PHP_EOL;
查看更多
登录 后发表回答