如何仅从当前月份显示MySQL查询结果?

时间:2016-09-09 21:28:52

标签: php mysql date datetime

我有以下PHP脚本,它从MySQL表中获取数据并将其打印在HTML表中。我想编辑数据只显示当月的信息。

在MySQL表格中,我的表格中有另一列InvoiceDateDATETIME类型,我可以用它来查看这些值是否来自本月。我希望调整我的查询或添加一段PHP代码,它将自动显示当月的结果,这样我就不需要每个月更新代码来显示新值。

实现这一目标的最佳方法是什么?

<?php

require_once 'config.php';

// create connection
$conn = new mysqli($currentConfig['host'], $currentConfig['user'], $currentConfig['pass'], $currentConfig['name']);
// check connection
if ($conn->connect_error) {
die('Connection failed: '.$conn->connect_error);
}

$sql = "SELECT SUM(InvoiceAmount) AS TotalBilling,SUM(ClientCostToDate) AS WIP FROM Estimates";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
 while ($row = $result->fetch_assoc()) {
  $wip = $row['WIP'];
  $total_billing = $row['TotalBilling'];

  // echo data into HTML table
  echo
  '<tbody>'.'<tr>'.'<td>'.$total_billing.'</td>'.'<td>'.$wip.'</td>'.'</tr>'.'</tbody>';
}
} else {
echo 'No results';
}
$conn->close();

我尝试了在Stack Overflow上找到的这个查询,但它不起作用:

SELECT InvoiceDate, SUM(InvoiceAmount) AS TotalBilling,SUM(ClientCostToDate) AS WIP FROM Estimates WHERE DATE_FORMAT(InvoiceDate,"%m")=DATE_FORMAT(NOW(),"%m");

我也发现了这个查询,它也不起作用:

SELECT InvoiceDate, SUM(InvoiceAmount) AS TotalBilling, SUM(ClientCostToDate) AS WIP FROM Estimates WHERE MONTH(InvoiceDate) = MONTH(now()) AND YEAR(InvoiceDate) = MONTH(now());

到目前为止,唯一适合我的是这个查询:

SELECT SUM(InvoiceAmount) AS TotalBilling,SUM(ClientCostToDate) AS WIP FROM Estimates WHERE InvoiceDate > '2016-09-01';

这显示本月的结果很好,但显然不理想,因为我必须逐月编辑查询。

1 个答案:

答案 0 :(得分:2)

使用DATE_FORMAT

SELECT SUM(InvoiceAmount) AS TotalBilling,SUM(ClientCostToDate) AS WIP 
FROM Estimates
WHERE date_format(InvoiceDate, '%Y-%m')=date_format(now(), '%Y-%m')