如何在PHP codeigniter中通过上个月的where条件?

如何在PHP codeigniter中通过上个月的where条件?,php,mysql,codeigniter,Php,Mysql,Codeigniter,我想从我的数据库中获取上个月和上周的记录 我在数据库中有登录和注销数据,我还提交了名为date_的数据,即日期 现在,我通过以下方式获取数据: public function monthly_login($emp_id = NULL) { $emp_id = $this->session->userdata('emp_id'); $this->db->select('*'); $this->db->from('dail

我想从我的数据库中获取上个月和上周的记录

我在数据库中有登录和注销数据,我还提交了名为date_的数据,即日期

现在,我通过以下方式获取数据:

public function monthly_login($emp_id = NULL)
{

      $emp_id = $this->session->userdata('emp_id');

      $this->db->select('*');

      $this->db->from('daily_data2');

      //$this->db->where('MONTH(date_data)', date('1-m'));

      $this->db->where('users.emp_id',$emp_id);

      $this->db->where('entry >','100');

      $this->db->order_by("date_data","ASC");

      $this->db->join('users', 'users.emp_id = daily_data2.emp_id','inner');

      $query = $this->db->get();



       $res   = $query->result();        

      return $res;

 }
我不知道在我的where条件下我应该通过什么,这样我才能得到上个月和上周的数据

$this->db->where("date_data BETWEEN {$startDate} AND {$endDate} ");
这里的$startDate和$endDate可以通过php的date和strottime函数进行计算,如下所示

$startDate = new DateTime();
$startDate->modify( 'first day of last month' );

$endDate   = new DateTime();
$endDate->modify( 'last day of last month' );
过去7天

 $startDate = date('y-m-d',strtotime("-1 week"), "\n";)
 $endDate   = date('y-m-d',strtotime("now"), "\n";)
过去30天

 $startDate = date('y-m-d',strtotime("-30 days"), "\n";)
 $endDate   = date('y-m-d',strtotime("now"), "\n";)
所以你可以用这种方式

根据您的评论,您需要上个月的数据,而不考虑当前日期。在这种情况下,您必须按如下方式计算日期范围

$startDate = new DateTime();
$startDate->modify( 'first day of last month' );

$endDate   = new DateTime();
$endDate->modify( 'last day of last month' );
如果您使用的是DateTime对象,那么您必须像这样更新查询

$this->db->where("date_data BETWEEN '" . $startDate->format( 'Y-m-d' ) . "' AND '" . $endDate->format( 'Y-m-d') . "' ");
试试这个

本周:

$this->db->where('date_data <=','DATE_ADD(NOW(),INTERVAL 7 DAYS )');
$this->db->where('date_data <=','DATE_ADD(NOW(),INTERVAL 30 DAYS )');

您想要上个月和上周的数据,还是只想要上个月的上周数据?不,我想要上个月的数据,即当前数据的12月和上周month@PradeepSanjaya我将为一周写另一个方法,但是where条件呢?但是我只需要上个月的数据,我不想在函数之间使用,你是说你上个月的数据不完全是最近30天的数据正确吗?因此,对于1月5日或1月31日访问数据的用户来说,您希望12月份的数据正确吗?在这种情况下,您可以检查并使用now函数中的“last month”(上个月)功能,该功能可以工作什么是$start和$end数据?让我们随时提供帮助。如果成功了,那么别忘了标记。是的,当然,让我交叉检查,我一定会这样做。嘿,不应该是DATE_SUB吗?因为它显示的是11月份的数据,我也只需要上月的数据,而不是所有的数据。我应该为上月的数据做些什么
$this->db->where('date_data <=','DATE_ADD(NOW(),INTERVAL 1DAY - INTERVAL 1 MONTH,"%Y-%m-01")');
$this->db->where('timestamp >=','DATE_ADD(NOW(),INTERVAL 1DAY - INTERVAL 1 MONTH,"%Y-%m-01")');