我正在尝试以今天的ctime
来获取任何记录。对于某些原因,&明天和&昨天没有任何值。如果删除strtotime()
,则它们的值是从mktime
派生的日期的字符串表示形式。 strtotime
我在做什么错?
PHP:
public function fetchToday()
{
$tomorrow = strtotime(mktime(0, 0, 0, date("m") , date("d")+1, date("Y")));
$yesterday = strtotime(mktime(0, 0, 0, date("m") , date("d")-1, date("Y")));
$q = "SELECT * FROM $this->_table WHERE ctime < $tomorrow AND ctime > $yesterday";
return $this->fetchBySelect($q);
}
错误:
ModelFactory - 'ERROR: syntax error at or near "AND"
LINE 1: SELECT * FROM motd WHERE ctime < AND ctime >
PostrgeSQL表字段:
ctime timestamp(0) with time zone
查询:
SELECT * FROM motd WHERE ctime < 1372402800 AND ctime > 1372230000;
`
到目前为止,所有答案都集中在php方面,但另一方面,我想说的正确解决方案是使用PostgreSQL功能,并将php代码更改为:
public function fetchToday()
{
$q = "SELECT * FROM $this->_table WHERE ctime < 'tomorrow'::timestamptz AND ctime > 'yesterday'::timestamptz;";
return $this->fetchBySelect($q);
}
为什么不只是:
$tomorrow = date("Y-m-d", strtotime("+1 day")); // sets tomorrow = 2013-06-28
$yesterday = date("Y-m-d", strtotime("-1 day")); // sets tomorrow = 2013-06-26
这是假设您的ctime列是MySQL datetamp。如果是unix时间戳,则:
$tomorrow = strtotime("+1 day");
$yesterday = strtotime("-1 day");
由于strtotime将参数转换为unix时间戳。您的代码使用strtotime和mktime都是多余的。
编辑:根据之前的文章,您的ctime列看起来像是unix时间戳,所以我的第二个示例是解决方法。 strtotime("+1 day")
将返回一个整数,该整数表示NOW + 1
Day的unix时间戳,并反向显示-1 Day
。
找不到答案
找不到答案
找不到答案
我认为这些语句中有错误,因此它们会产生空字符串并使查询失败。
$tomorrow = strtotime(mktime(0, 0, 0, date("m") , date("d")+1, date("Y")));
$yesterday = strtotime(mktime(0, 0, 0, date("m") , date("d")-1, date("Y")));
mktime()返回unix时间戳,您不需要使用strtime()。
这取决于您如何在数据库中存储数据。如果将它们保留为TIMESTAMP,则只需省略strtotime。
如果将它们保留为ISO之类的“ YYYY-MM-DD”,则仅使用date()。
public function fetchToday()
{
$tomorrow = strtotime("+1 day", strtotime(date("Y-m-d H:i:s")));
$yesterday= strtotime("-1 day", strtotime(date("Y-m-d H:i:s")));
$q = "SELECT * FROM ".$this->_table." WHERE ctime < ".$tomorrow." AND ctime > ".$yesterday;
return $this->fetchBySelect($q);
}