Compare two dates in Codeigniter and MySQL

idontknowhow picture idontknowhow · Jun 9, 2011 · Viewed 22.6k times · Source

How can I get values between two dates in Codeigniter query function? Here is my model and sample code.

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;
}

But it doesn't work, here is the error I got

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

Answer

danneth picture danneth · Jun 9, 2011

I think you need qoutes around your date (i.e. '2011-06-08'). try this

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;
}

If your columns event_startdate and event_enddate are DATETIME type but you are only interested in the date part you can do `DATE(event_enddate) to extract the date part