简体   繁体   中英

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

my database table looks like below

| id | user_name | address | contact | date | |----|-----------|---------|---------|----------| | 1 | john | NY | 12345 |2015-4-20 | | 2 | Mart | NY | 54345 |2015-4-05 | | 3 | Drew | US | 67340 |2015-3-14 |

my controller function is

function orders()
{

  $data['orders'] = $this->common_model->get_data_between_15days('tbl_orders',array('status'=>'1'));
  $data['title']='Orders';
  $data['main_content']='users/orders_view.php';
  $this->load->view('admin/includes/template',$data);

}

and my model function is

   public function get_data_between_15days($table, $condition)
   { 

    $result = $this->db->get_where($table, $condition);
    if($result)
      {
        return $result->result_array();
      }
   }

now i want to get the records between today and last 15 days from database.and i tried like this

 $result = $this->db->query('SELECT * FROM '.$table.' WHERE date BETWEEN DATE_SUB(NOW(), INTERVAL 15 DAY) AND NOW(); AND '.$condition);

but its not working. i want to get all the Records between Last 15 and 30 Days too. I would appreciate for your help. thank you.

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

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

您可以使用以下查询根据您的 localhost 时区获取过去 15 天的数据,因为您的 MYSQL 数据库时区可能与您的 localhost 不同,那么您将无法从数据库中获得正确的数据。

 $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);

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

我认为最好的方法您可以使用 dateiff 按天数来获取任何两个日期之间的任何查询

    $result  = $this->db->query("SELECT * FROM ".$table." WHERE datediff('". $your_date ."', row_date) <= 15")->get()->result();

Updating answer to CI 4 at 2021

$myModel = new WhateverModel();

$result = $myModel->where("date BETWEEN DATE_SUB(NOW(), INTERVAL 15 DAY) AND NOW()")->findAll();

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