在我的 php mysql 报告中,我使用以下代码从 mysql 表中提取数据。一切工作正常,但我最终无法完成总和。有什么方法可以总结员工的工作时间。 (我尝试翻转,它不满足我的要求,任何专家都可以指导我如何处理循环,以便我可以获得如下图所示的输出
$sql = "SELECT * FROM timetablw ORDER BY id DESC limit 30";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '<table class="table table-bordered table-striped">';
echo "<thead>";
echo "<tr>";
echo "<th>Emp-Id</th>";
echo "<th>Name</th>";
echo "<th>Company</th>";
echo "<th>Date</th>";
echo "<th>worktime</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['empid'] . "</td>";
echo "<td>" . $row['empname'] . "</td>";
echo "<td>" . $row['company1'] . "</td>";
echo "<td>" . date('d-M-Y', strtotime($row['date1'])) . "</td>";
echo "<td>" . $row['wrktime'] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo '<div class="alert alert-danger"><em>No records were found.</em></div>';
}
要计算“工作时间”列的总和,您可以在循环之前初始化一个变量以累积值并在循环内更新它。这是代码的修改版本,其中包含总和计算:
$sql = "SELECT * FROM timetablw ORDER BY id DESC LIMIT 30";
if ($result = mysqli_query($link, $sql)) {
if (mysqli_num_rows($result) > 0) {
echo '<table class="table table-bordered table-striped">';
echo "<thead>";
echo "<tr>";
echo "<th>Emp-Id</th>";
echo "<th>Name</th>";
echo "<th>Company</th>";
echo "<th>Date</th>";
echo "<th>worktime</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
$totalWorkTime = 0; // Initialize the variable for sum
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['empid'] . "</td>";
echo "<td>" . $row['empname'] . "</td>";
echo "<td>" . $row['company1'] . "</td>";
echo "<td>" . date('d-M-Y', strtotime($row['date1'])) . "</td>";
echo "<td>" . $row['wrktime'] . "</td>";
// Update the sum variable
$totalWorkTime += $row['wrktime'];
echo "</tr>";
}
echo "</tbody>";
// Display the sum row
echo "<tfoot>";
echo "<tr>";
echo "<td colspan='4'><strong>Total Work Time:</strong></td>";
echo "<td><strong>" . $totalWorkTime . "</strong></td>";
echo "</tr>";
echo "</tfoot>";
echo "</table>";
// Free result set
mysqli_free_result($result);
} else {
echo '<div class="alert alert-danger"><em>No records were found.</em></div>';
}
}
此修改包括一个变量
$totalWorkTime
,该变量在循环之前初始化并在循环内更新以累积值。然后,总和将显示在表页脚的新行中。根据需要调整格式。