简体   繁体   中英

listing records in given date range in Codeigniter

I have a database that hold records with dates in form of varChar

my database:

------------------------
| id | name |    date  |
------------------------
| 1 | Mark  |01-11-2020|
------------------------
| 2 | Mark  |01-06-2020|
------------------------
| 3 | Mark  |01-07-2020|
------------------------

the date format is day-month-year

i have 2 string variables:

var1: 01-05-2020
var2: 20-06-2020

when i enter there variables to my sql i dont get the right result which is

01-06-2020

my code is

    $this->db->order_by('id', 'DESC');
    $this->db->where('date >=', '01-05-2020');
    $this->db->where('date <=', '20-06-2020');
    $query = $this->db->get('db');
    $data["records"] = $query->result();

you need to convert string you are trying to search too

    $this->db->order_by('id', 'DESC');
    $this->db->where("STR_TO_DATE(date,'%d-%m-%Y') >=", "STR_TO_DATE('01-05-2020','%d-%m-%Y')");
    $this->db->where("STR_TO_DATE(date,'%d-%m-%Y') <=", "STR_TO_DATE('20-06-2020','%d-%m-%Y')");
    $query = $this->db->get('db');
    $data["records"] = $query->result();

you may find this fiddle helpful

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