简体   繁体   English

Codeigniter:如何从数据库中获取今天和过去 15 天之间的数据

[英]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我的controller功能是

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我的model功能是

   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现在我想从数据库中获取今天和过去 15 天之间的记录。我试过这样

 $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.我也想获得过去 15 天到 30 天之间的所有记录。 I would appreciate for your help.我将不胜感激您的帮助。 thank you.谢谢你。

Use CodeIgniter standard of query使用 CodeIgniter 标准查询

$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 NOW()函数后的分号,分号是中断查询,因此 YySql 理解分号后的另一个查询
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 2021 年更新 CI 4 的答案

$myModel = new WhateverModel();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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