-
今天的日期是2013年4月25日。是的,服务器上的时间是正确的,并且
mdate('%Y-%m-%d', strtotime(now()))
的var_dump
正在返回2013-04-25
。 -
date
的MySQL表列为date
类型/格式。 -
CodeIgniter 2.1.3
-
我的搜索条件字符串是
"test"
。
$criteria = array(
'field1' => 'test',
'field2' => 'test',
'field3' => 'test'
);
我的数据库中包含"测试"一词的四个项目的日期如下:
date
2013-04-02
2013-04-05
2013-05-07
2013-05-21
在我的模型中,当我希望我的搜索结果(search="test"(无论日期如何都能返回所有内容时,这就是它的样子。。。
$this->db->start_cache();
$this->db->or_like($criteria);
$this->db->order_by('date', 'desc');
$this->db->stop_cache();
$query['results'] = $this->db->get('table', $limit, $offset)->result_array();
$this->db->flush_cache();
return $query;
预期输出:
2013-05-21
2013-05-07
2013-04-05
2013-04-02
以上操作非常完美,四件物品都已退回。
然而,当使用这一点时,只添加了一个where()
来将结果细化到今天甚至更大。。。
$this->db->start_cache();
$this->db->or_like($criteria); // <-- remove this line and it works
$this->db->where('date >=', mdate('%Y-%m-%d', strtotime(now()))); // <-- only new line
$this->db->order_by('date', 'asc');
$this->db->stop_cache();
$query['results'] = $this->db->get('table', $limit, $offset)->result_array();
$this->db->flush_cache();
return $query;
意外输出:
2013-04-02 // <-- why this one??? today is 4/25
2013-05-07
2013-05-21
它应该只显示今天和未来的结果那么,为什么日期为2013年4月2日的项目在那里,而今天是2013年4月份25日(它好像部分工作了,因为它仍然忽略了带有2013-04-05
的项目。(
- 为什么会发生这种情况
- 如何解决这个问题
编辑:
我试着颠倒订单:
$this->db->where('date >=', mdate('%Y-%m-%d', strtotime(now())));
$this->db->or_like($criteria);
和链接:
$this->db->or_like($criteria)->where('date >=', mdate('%Y-%m-%d', strtotime(now())));
这个:
$this->db->or_like($criteria);
$this->db->where('DATE(date) >= DATE(NOW())');
结果是一样的。
首先,为什么不使用MySQL函数进行日期/时间:
$this->db->where('DATE(date) >= DATE(NOW())');
(您可能不需要DATE(DATE(,但只需要DATE(
然而,正如注释中所述,在and
和or
方面,您的查询可能没有按照您的意愿生成。要测试输出查询的外观,请使用echo $this->db->last_query();
。您总是可以使用自定义字符串编写活动记录查询的where部分,就像我上面的例子一样,这应该可以解决和/或问题。
所有这些都应该能帮助你解决问题。
编辑
聊天后,这是最终的解决方案:
$where = "DATE(date) >= DATE(NOW())
AND
(event LIKE '%$your_string%'
OR location LIKE '%$your_string%'
OR description LIKE '%$your_string%')";
$this->db->where($where);
我在ellislab论坛上找到了答案https://ellislab.com/forums/viewthread/185983/而不是使用
$this->db->like('location', $your_string);
用途:
$this->db->where('location LIKE', '%'.$your_string.'%');
和或_where而不是或者_like。