我有一个根据时间计算成本的表,我需要根据时间限制显示1小时的表。如果时间大于1小时,则应在“费用”列中显示null。我该怎么办。
dashboard.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db_name = "test2";
$lastId="";
$date = strtotime('now') - 3600;
print_r($date);
$week = strtotime('now') - 604800;
$month = strtotime('now') - 2592000 ;
//create connection
$con = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
$result = mysqli_query($con,"SELECT SUM(cost) FROM track_data WHERE start_time >
DATE_SUB(NOW(), INTERVAL 1 HOUR) ");
$result1 = mysqli_query($con,"SELECT SUM(cost) FROM track_data WHERE start_time >
DATE_SUB(NOW(), INTERVAL 1 WEEK)");
$result2 = mysqli_query($con,"SELECT SUM(cost) FROM track_data WHERE start_time >
DATE_SUB(NOW(), INTERVAL 1 MONTH)");
?>
<div class="col-md-6 col-md-offset-3">
<table class="table table-hover table-striped">
<tr class="t_head">
<th> Days </th>
<th> Usage </th>
<th> Total Cost </th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
echo "<tr id='emp_salary'>";
echo "<td> Today </td>";
echo "<td>1 Hour</td>";
echo "<td>" .$row[0]. "</td>";
echo "</tr>";
}
?>
</table>
</div>
如您所见,上图的总费用列为空。代替空值,我应该得到NUll或零。
答案 0 :(得分:3)
您应该使用COALESCE
因为如果您的sql查询不返回任何行或行的总和为null,那么您的回声实际上不会回显任何内容。
尝试一下
$result = mysqli_query($con,"SELECT COALESCE(SUM(cost),0) FROM track_data
WHERE start_time > DATE_SUB(NOW(), INTERVAL 1 HOUR) ");