Rajan Rajan - 4 years ago 427
PHP Question

How to pass last month in where condition in PHP codeigniter?

i want to fetch records of last month and last week from my database.

I have login and logout data in database also i have filed called date_data which is the date.

Now i am fetching my data by this:

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;

}


I dont know what should i pass in my where condition so that i get last month and last week's data

Answer Source
$this->db->where("date_data BETWEEN {$startDate} AND {$endDate} ");

Here $startDate and $endDate you can Calculate via php's date and strtotime function as follows

For last 7 days

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

For last 30 days

 $startDate = date('y-m-d',strtotime("-30 days"), "\n";)
 $endDate   = date('y-m-d',strtotime("now"), "\n";)

So you can use in this way

As For your Requirement based on your comment that you want the data of last month regardless of the current date in that case you have to calculate the date range as follows

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

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

In case you are using DateTime object in that case you have to update your Query like this.

$this->db->where("date_data BETWEEN '" . $startDate->format( 'Y-m-d' ) . "' AND '" . $endDate->format( 'Y-m-d') . "' ");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download