Codeigniter: how to get data between today and last 15 days from database

前端 未结 5 396
谎友^
谎友^ 2021-01-13 00:55

my database table looks like below

| id | user_name | address | contact | date | |----|-----------|---------|---------|----------| | 1 | john | NY

相关标签:
5条回答
  • 2021-01-13 01:02

    You can use the following query to get last 15 days data based on your localhost time zone as may be your MYSQL database time zone is different than your localhost then you will not get correct data from database.

     $result = $this->db->query('SELECT * FROM '.$table.' WHERE date >= '.date('Y-m-d', time() - (15 * 24 * 60 * 60)).' AND date <= '.date('Y-m-d').' AND '.$condition);
    
    0 讨论(0)
  • 2021-01-13 01:07

    Use CodeIgniter standard of query

    $this->db->select('*');
    $this->db->where('date BETWEEN DATE_SUB(NOW(), INTERVAL 15 DAY) AND NOW()');
    $this->db->where($conditions);
    $result = $this->db->get($table);
    
    0 讨论(0)
  • 2021-01-13 01:14

    I think the best way You can use dateiff to get any query between any two dates by days like this

        $result  = $this->db->query("SELECT * FROM ".$table." WHERE datediff('". $your_date ."', row_date) <= 15")->get()->result();
    
    0 讨论(0)
  • 2021-01-13 01:19

    Remove ; semicolon after NOW() function, semicolon is break query so YySql understand another query after semicolon
    this query would work

     $result = $this->db->query('SELECT * FROM '.$table.' 
     WHERE `date` BETWEEN DATE_SUB(NOW(), INTERVAL 15 DAY) AND NOW() AND '.$condition);
    
    0 讨论(0)
  • 2021-01-13 01:20

    This is how you can achieve:

    $qs = "";
    if( is_array($condition) && count($condition) > 0 ):
        foreach( $condition as $_k => $_v ) {
            $qs .= "and $_k = {$_v} ";
        }
    endif;
    
    'SELECT * FROM '.$table.'  
        WHERE `date` BETWEEN DATE_SUB(NOW(), INTERVAL 15 DAY) AND NOW() '.$qs
    
    0 讨论(0)
提交回复
热议问题