获取搜索月份之前的天数总和

时间:2017-11-25 07:49:37

标签: php mysqli

我在下面的结构中留下详细信息表。

emp_id     leave_from      leave_to     total_days
  1        2017-08-01     2017-08-04       3
  1        2017-09-10     2017-09-12       2

当我搜索9月份时,我想显示总数= 3,当它是10月份搜索时,总计= 5。

我试过下面的代码。但它给了我每个月搜索的总和。

$result4 = mysqli_query($connection, "SELECT SUM(total_days) as total FROM leave_details l WHERE l.emp_id='$empId' AND status=1 AND YEAR(l.leave_from)='$yearSearch' GROUP BY YEAR(l.leave_from)");

 $row = mysqli_fetch_array($result4); 
  echo $row['total'];

有人可以协助我解决疑问吗?谢谢。

1 个答案:

答案 0 :(得分:1)

您使用GROUP BY YEAR的查询,

您需要更改为使用GROUP BY MONTH ...并且您将获得今年现有月份的总计leavs列表

$result4 = mysqli_query($connection, "SELECT SUM(total_days) as total FROM leave_details l WHERE l.emp_id='$empId' AND status=1 AND YEAR(l.leave_from)='$yearSearch' GROUP BY MONTH(l.leave_from)");

然后你需要获取列表并迭代foreach ...

您可以看到http://php.net/manual/en/mysqli-result.fetch-assoc.php了解更多信息

while ($row = $result4->fetch_assoc()) {
    echo $row['total'].'<br />';
}

如果您只需要特定年份+月份并且只获得1个结果,

尝试使用此查询

$result4 = mysqli_query($connection, "SELECT SUM(total_days) as total FROM leave_details l WHERE l.emp_id='$empId' AND status=1 AND YEAR(l.leave_from)='$yearSearch' AND MONTH(l.leave_from)")='$monthSearch';

$row = mysqli_fetch_array($result4); 
echo $row['total'];

如果您想要特定年份,直到某个月...只需更改查询的MONTH部分中的运算符... &lt;而不是=

$result4 = mysqli_query($connection, "SELECT SUM(total_days) as total FROM leave_details l WHERE l.emp_id='$empId' AND status=1 AND YEAR(l.leave_from)='$yearSearch' AND MONTH(l.leave_from)")<'$monthSearch';