I want to make a summary script, for example, how many new users are there today, yesterday, this week, last week, this month, last month, so on.
I’m using CodeIgniter, so I wonder which one is better? Using multiple calls on models like this :
$this->model->get_today_users();
$this->model->get_yesterday_users();
$this->model->get_this_week_users();
// so on
Each one of the functions above only return the number of users with specific date range (e.g. SELECT COUNT(*) WHERE join_date=NOW() for today_users , etc – of course using CI active record ).
Or is it better having one single query with all necessary subqueries like this :
function stats(){
$this->db->select('*');
$this->db->select('(SELECT COUNT(*) FROM users WHERE join_date=NOW()) as today');
$this->db->select('(SELECT COUNT(*) FROM users WHERE join_date=NOW()-INTERVAL 1 DAY) as yesterday');
$this->db->select('(SELECT COUNT(*) FROM users WHERE WEEK(join_date)=WEEK(NOW()) ) as this_week');
$this->db->select('(SELECT COUNT(*) FROM users WHERE WEEK(join_date)=WEEK(NOW())-1 ) as last_week');
$this->db->select('(SELECT COUNT(*) FROM users WHERE MONTH(join_date)=MONTH(NOW()) ) as this_month');
$this->db->select('(SELECT COUNT(*) FROM users WHERE MONTH(join_date)=MONTH(NOW())-1 ) as last_month');
$this->db->from('users');
$ret = $this->db->get();
}
and then calling for example $data[‘stat’] = $this->model->stats(); so in views, I can call $stat->today, $stat->this_week, etc.
Thanks in advance for the answers.
UPDATE : What if I want to make a function that receives a date? Let’s say I have to loop a month like this:
//for the sake of simplicity
foreach(day in a month as $r){
$this->model->get_user_on_this_day($r);
}
This means for a 30-day month, it will loop 30 times! Is there any better way than that?
IMO, neither of the approach is optimized.
Using least query is the best, so, you should do a GROUP BY query like below :
Once you have the result, which you can set an array using date as key,
then you can further group by day, week, month…(whatever you want)
Seems like OP don’t understand how this work :-
The above query is doing a one-time query, and will return the rows like
All you have to do is to iterate the results (not active record)
By the end of the loop, $total = total user registered from $start until $end.
Is more effective and optimize then doing 30 (or 31) queries during the loop of month-day.