gpt4 book ai didi

php - Mysql SUM() 与 PHP 普通加法运算

转载 作者:行者123 更新时间:2023-11-29 06:52:08 38 4
gpt4 key购买 nike

在我正在开发的程序中,我有一个表格显示用户在每项任务上花费了多少时间。我想显示任务时间列的总计。

由于 tfoot 位于 while 语句之外,因此我使用不同的查询来计算总计。这个Pen代表它现在的样子。

如您所见,问题在于 $grandtotal 不等于所有 $tasktime 的总和。我怎样才能做到这一点?

总计查询

$stots ="SELECT *,  SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(te.date_end, te.date_start)))) 
AS Duration FROM taskentries";
$resultots=mysqli_query($db,$stots);
$totaltime =mysqli_fetch_assoc($resultots);
$grandtotal = $totaltime['Duration'];

    <table>
<thead>
<th>Task</th>
<th>Date Start</th>
<th>Date End</th>
<th>Time On Task</th>
</thead>
<tfoot>
<tr>
<td th='Task'></td>
<td th='Date Start'></td>
<td th='Date End'>Grand Total</td>
<td th=''>
<?php
if($grandtotal < 0){
echo '0';
}else{
echo $grandtotal;
}?>

</td>
</tr>
</tfoot>
<tbody>

<?php
$sql="SELECT * FROM taskentries";
$result=mysqli_query($db,$sql);
while($taskentry=mysqli_fetch_array($result)){ ?>
<tr>
<td th='Task'><?=$taskentry['task'];?></td>
<td th='Date Start'><?=$taskentry['date_start'];?></td>
<td th='Date End'><?=$taskentry['date_end'];?></td>
<td th='Time On Task'>
<?php
$date_start = date("h:i:sa",strtotime($taskentry['date_start']));
$date_end = date("h:i:sa",strtotime($taskentry['date_end']));
$tasktime = $date_end - $date_start;
if($tasktime < 0){
echo '0';
}else{
echo $tasktime;
}?>
</td>
</tr>
<?php };?>
</tbody>
</table>

最佳答案

在 PHP 中,您将 $date_start$date_end 设置为 "12:34:56am" 等字符串,然后减去它们。减法仅适用于数字,它不知道任何关于时间的信息,因此这样的字符串会转换为数字12。因此,如果您从“07:12:55”中减去“05:14:33”,它只会返回 2,因为它正在执行 7-5。此外,当数字以 0 开头时,它会被视为八进制,仅允许从 07 的数字。因此,以 08:09: 开头的时间将被视为 0,因为 8 9 不是有效数字。

strtotime() 返回一个时间戳,即秒数,您应该只减去它们,而不是调用 date()。然后您可以将其转换为时间。

         $date_start = strtotime($taskentry['date_start']);
$date_end = strtotime($taskentry['date_end']);
$tasktime = max(0, $date_end - $date_start); // don't show negative times
echo date("H:i:s", $tasktime");

请注意,date() 旨在打印转换为日期和时间,而不是持续时间。如果 $tasktime 超过 24 小时,则不会给出正确答案。您应该考虑转换为 DateInterval

关于php - Mysql SUM() 与 PHP 普通加法运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47044413/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com