I have a tables with many actions, a field is “created” with the datetime of the action.
I need to get back an array with how many actions I registered per HOUR, WEEK DAY, DAY, MONTH in a periode range.
Is better doing a unique db request and parsing all results
foreach($scans as $s) {
$data['total']++;
$t = strtotime($s['Scan']['created']);
//week day
@$data['weekday'][date('w',$t)]++;
@$data['hour'][date('H',$t)]++;
@$data['day'][date('d',$t)]++;
@$data['month'][date('n',$t)]++;
}
or 5 queries with count() function?
Thanks
A database is equipped to perform exactly this sort of tasks with the best efficiency. You should offload most of data processing to the database system, which will do all sort of optimizations for you, and leave PHP for managing and presentation. In principle you should avoid looping over data in PHP to do processing, unless you are doing presentation stuff.
So you should do your entire thing in ONE query, and get the final result from your database. Look at your query and try to combine all the things you want into it. Maybe you can try to get help from Stack Overflow if you can’t come up with the right query (but open another question for it).