【发布时间】:2013-01-06 22:40:46
【问题描述】:
我想使用 PHP 过滤我的结果以仅显示今天插入的表中的数据。格式如下:
表格daily中的列date,格式为2013-01-06 17:36:11。如何使用 PHP 过滤查询以仅显示今天的查询?
【问题讨论】:
我想使用 PHP 过滤我的结果以仅显示今天插入的表中的数据。格式如下:
表格daily中的列date,格式为2013-01-06 17:36:11。如何使用 PHP 过滤查询以仅显示今天的查询?
【问题讨论】:
WHERE DATE(`date`) = DATE(NOW())
【讨论】:
` 而不是' 对于(`date`)。另外,为什么您的查询有效但WHERE date = NOW() 无效?
2013-01-06 17:36:11 的NOW() 在我的数据库中插入了一个日期时间,那么为什么NOW() 前面的DATE 是必要的?
DATE(2013-01-06 17:36:11) == 2013-01-06,DATE(NOW()) 也是如此
最好在 sql 查询的 where 子句中进行操作。扩展宇智波斑的回答:如果您使用的是 MySQL,您的查询将类似于:
SELECT * FROM daily WHERE DATE(`date`) = DATE(NOW()).
如果您出于某种奇怪的原因必须在 PHP 中执行此操作(我不推荐),则必须循环查询结果并比较PHP 中每个数据库行的日期字段与今天的日期。
//setup the array our filtered results will go in
$filteredResults = array();
//get the timestamp for 12:00:00am and 11:59:59pm today
$greaterThanThisTime = mktime(0,0,0,date('n'),date('j'),date('Y'));
$lessThanThisTime = mktime(23,59,59,date('n'),date('j'),date('Y'));
//loop the database results
foreach($dbResults as $i=>$row) {
$rowTimeStamp = strtotime($row['date']);
if($rowTimeStamp>=$greaterThanThisTime && $rowTimeStamp<=$lessThanThisTime) {
$filteredResults[] = $row;
}
}
//continue to do whatever you need, using $filteredResults as your results
【讨论】: