我想从我的数据库中获取上个月和上周的记录。
我在数据库中有登录和注销数据,我也提交了名为date_data的日期。
现在我通过这个获取我的数据:
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;
}
我不知道我应该在哪里通过,以便我上个月和上周的数据
答案 0 :(得分:4)
$this->db->where("date_data BETWEEN {$startDate} AND {$endDate} ");
这里$ startDate和$ endDate你可以通过php的日期和strtotime函数计算如下
最近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对象,你必须像这样更新你的Query。
$this->db->where("date_data BETWEEN '" . $startDate->format( 'Y-m-d' ) . "' AND '" . $endDate->format( 'Y-m-d') . "' ");
答案 1 :(得分:3)
试试这个......
周:
$this->db->where('date_data <=','DATE_ADD(NOW(),INTERVAL 7 DAYS )');
月份:
$this->db->where('date_data <=','DATE_ADD(NOW(),INTERVAL 30 DAYS )');
上个月从第1天开始
$this->db->where('date_data <=','DATE_ADD(NOW(),INTERVAL 30 DAYS,"%Y-%m-01")');
尝试下列任一项:
$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")');