简体   繁体   中英

CodeIgniter Record Selection between two dates

I am using CodeIgniter and I want the help on following issue. I provide some start date and end date and I want to see what are reservations on or between these provided dates.

$startdate = '2016-05-23';
$enddate = '2016-05-27';

$this->$db->select('reservationid, startdate, enddate');
$this->$db->from('reservation');
$this->$db->where('startdate >=', $startdate);
$this->$db->where('enddate <=', $enddate);
$query = $this->$db->get()->result_array();

return $query;

Result = Array ( [0] => Array ( [reservationid] => KHAN2016Q224 [startdate] => 2016-05-23 [enddate] => 2016-05-27 ) )

Above query returns above result.

But when I provide

$startdate = '2016-05-24';
$enddate = '2016-05-26'; 

then it returns an empty array. I want that the above reservationid should be returned again when I search between dates as on this date there is some reservation and I dont want it to exclude.

If I understand correctly you want to return any reservation which has duration between two dates, so you can write your custom WHERE part.

$startdate = '2016-05-23';
$enddate = '2016-05-27';

$this->$db->select('reservationid, startdate, enddate');
$this->$db->from('reservation');
$this->$db->where('(startdate BETWEEN "' . $startdate . '" AND "' . $enddate . '") OR (enddate BETWEEN "' . $startdate . '" AND "' . $enddate . '")');
$query = $this->$db->get()->result_array();

return $query;

Of course you need to properly escape $startdate and $enddate or do a check that they are proper dates by creating DateTime class from those dates.

Try this below query, It's working for me.

$this->db->select('*');
$this->db->from('table');
$this->db->group_start();
    $this->db->where('start_date <=',$start_date);
    $this->db->where('end_date >=',$start_date);
$this->db->group_end();
$this->db->group_start();
    $this->db->where('start_date <=',$end_date);
    $this->db->where('end_date >=',$end_date);
$this->db->group_end();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM