我正忙着做这件事。我一直在寻找,我看到了我可以使用的不同东西,比如 CAST , date() function , SUM 、Javascript 数学等。问题是我不知道要使用哪一个,或者我会在我的情况下使用哪一个。我阅读不同主题和“解决方案”的次数越多,我就越对如何将其应用到我的需求感到困惑。
我的数据库中有一个名为“timesheet”的简单时间表表,其中有 entry_id (AI)、user_id、名字、姓氏、punch(日期时间)和 comment(输入/输出)列。我在 PHP 中做了一个简单的查询,将用户时间表导入到如下所示的 HTML 表格中。
在我的 PHP 查询中,我运行一个 WHILE 语句来遍历记录。因为我使用的是循环,所以我不知道如何/将如何计算时间来给出该时间段的总工作小时数。
这是我的查询:
$timesheet = mysqli_query($connect, "SELECT DATE_FORMAT(punch, '%Y/%m/%d') AS punch_date, DATE_FORMAT(punch, '%H:%i:%s') AS punch_time, comment
FROM timesheet WHERE user_id = '$employee' AND punch BETWEEN '$fromDate' AND '$toDate'") or die('Error: ' . mysqli_error($connect));
if(mysqli_num_rows($timesheet)>0){
$output = '<table class="table table-striped">
<thead>
<tr>
<th>Date</th>
<th>Time</th>
<th>Status</th>
</tr>
</thead>
<tbody>';
while ($row = mysqli_fetch_array($timesheet, MYSQL_ASSOC)) {
$date = $row['punch_date'];
$time = $row['punch_time'];
$status = $row['comment'];
$output .= '<tr>
<td>' . $date . '</td>
<td ';
if($status === 'In'){
$output .= 'class="in-time"';
} elseif($status === 'Out') {
$output .= 'class="out-time"';
}
$output .= '>' . $time . '</td>
<td>' . $status . '</td>
</tr>';
} //end while
$output .= '</tbody>
</table>';
echo $output;
} //end if mysqli_num_rows
甚至可以计算循环中的时间吗?如果是这样,您介意举个例子吗?如果不介意,您能否指出我哪里/哪里做错的方向?
更新: 每个时间条目都有 In 或 Out 作为状态,因此我需要获取每组 In 和 Out 的差异,然后将其相加以获得该时间段的总工作时间。最终这就是我需要完成的(见表底部的红色总计)
这是数据库表“timesheet”的快照
最佳答案
在 while() 之前,我们必须决定是否使用所有行来计算总时间。
因为这里有一个陷阱。如果用户已登录但尚未注销怎么办?
在这种情况下,我们不会在总计中使用上次登录时间。所以:
$iterations = mysqli_num_rows($timesheet) % 2 == 0 ? mysqli_num_rows($timesheet) : mysqli_num_rows($timesheet) - 1;
在您的 while 循环中,将 punch_time 转换为秒数。
while() {
...
$parts = explode(':', $row['punch_time']);
$seconds = (int) $parts[0] * 3600 + (int) $parts[1] * 60 + (int) $parts[2];
if($status === 'In'){
$output .= 'class="in-time"';
$total -= $iterations ? $seconds : 0; // Subtract from total when in and there is out coming
} else if($status === 'Out') {
$output .= 'class="out-time"';
$total += $seconds; // Add to total when out
}
...
$iterations--;
}
在循环之后,您可以使用
将秒数转换为您想要的格式$hours = floor($total / 3600);
$minutes = floor(($total / 60) % 60);
$seconds = $total % 60;
echo "$hours:$minutes:$seconds";
关于php - 在 while 语句 PHP/MYSQL 中从时间表计算时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26120941/