如何在Codeigniter查询功能中获取两个日期之间的值?这是我的模型和示例代码。
function get_promo() {
$today = date('Y-m-d');
$query = $this->db->query('SELECT FROM tbl_event WHERE event_id = $id AND event_startdate <= $today
AND event_enddate >= $today');
return $query;
}
但它不起作用,这是我得到的错误
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 ' at line 1
SELECT FROM tbl_event WHERE event_id = 36 AND event_startdate <= 2011-06-09 AND event_enddate >= 2011-06-09
Filename: C:\xampp\htdocs\hotel\system\database\DB_driver.php
Line Number: 330
答案 0 :(得分:6)
我认为您需要在约会时间(即“2011-06-08”)。试试这个
function get_promo() {
$today = date('Y-m-d');
$query = $this->db->query(
"SELECT FROM tbl_event WHERE event_id = {$id} AND event_startdate <= '{$today}'
AND event_enddate >= '{$today}'");
return $query;
}
如果您的列event_startdate
和event_enddate
是DATETIME
类型,但您只对日期部分感兴趣,可以执行`DATE(event_enddate)来提取日期部分
答案 1 :(得分:1)
我认为您需要使用date_format(),此链接中的更多信息http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format。
试试这段代码:
$today = date('Y-m-d');
$query = $this->db->query("SELECT FROM tbl_event WHERE event_id = $id AND DATE_FORMAT(event_startdate ,'%Y-%m-%d') >= DATE_FORMAT($today ,'%Y-%m-%d') AND DATE_FORMAT(event_enddate ,'%Y-%m-%d') <= DATE_FORMAT($today ,'%Y-%m-%d')");
答案 2 :(得分:1)
查看错误,似乎您的查询未正确转义。添加单引号或双引号来修复它。检查@danneth的答案。使用简单安全的Query Binding或更多使用Active Record。以下是基于您的代码的绑定和活动记录的示例。
查询绑定示例
$today = date('Y-m-d');
$sql = 'SELECT
*
FROM
tbl_event
WHERE event_id = ?
AND event_startdate <= ?
AND event_enddate >= ?';
$query = $this->db->query($sql, array($id, $today, $today));
return $query;
有效记录示例
$query = $this->db
->select('*')->from('tbl_event')
->where(array(
'event_id' => $id,
'event_startdate <= ' => $today,
'event_enddate >= ' => $today
))
->get();
return $query;
附加->result()
或->result_array()
等以获取对象或数组中的结果。查看Codeigniter Database User Guide了解更多信息。快乐的编码!
答案 3 :(得分:0)
您需要使用正确的格式。试试这个:
$todaystart = date('Y-m-d 00:00:00');
$todayend = date('Y-m-d 23:59:59');
$query = $this->db->query('SELECT FROM tbl_event WHERE event_id = $id AND event_startdate <= ? AND event_enddate >= ?', array($todaystart, $todayend));
编辑:您的查询错误。这样做:
$todaystart = date('Y-m-d 00:00:00');
$todayend = date('Y-m-d 23:59:59');
$query = $this->db->query('SELECT * FROM tbl_event WHERE event_id = $id AND event_startdate <= ? AND event_enddate >= ?', array($todaystart, $todayend));
答案 4 :(得分:0)
$this->db->where('date_start <=',date('Y-m-d'));
$this->db->where('date_end >=',date('Y-m-d'));
$query = $this->db->get('table');