I have this query
$query = mysql_query ("SELECT type, count(*), date FROM tracking WHERE htcode='$htG' AND type IN ('viewed', 'shared', 'printed', 'emailed', 'used') GROUP BY type, date ORDER BY date ASC");
This code:
while ($result = mysql_fetch_assoc($query)){
echo $result['date'] .' / ' .$result['type'].' = ' .$result['count(*)'];
echo '<br>';
}
gives me :
2012-02-01 / viewed = 2
2012-02-03 / emailed = 1
2012-02-04 / shared = 1
2012-02-05 / viewed = 1
2012-02-07 / viewed = 2
2012-02-07 / shared = 3
2012-02-07 / emailed = 1
2012-02-07 / printed = 1
How can i take the query array and pull all (viewed, shared, emailed, printed, used) for today, for yesterday, and for a date range (last 30 days for example)?
To get all results for a specific date range, don’t group by date; instead use a WHERE clause to limit the date of the count. Otherwise the query is very similar.
Here’s just the query itself formatted over several lines for clarity:
Just make sure you set the values for
$start_dateand$end_datefirst. For example, for today you’d just set them both to this:Note that
date('Y-m-d')is just today’s date in a format likeYYYY-MM-DD.For yesterday, you’d pass in yesterday’s timestamp into the date() function, but use the same format:
And for the past thirty days, you’d start 30 days ago and end today:
You can do it like this for any start/end date. Note that I’m using strtotime(), which lets you use a lot of English phrases to specify timestamps rather than having to do date arithmetic.
Also, since you will be doing the query multiple times, it would probably make sense to separate out the logic into its own function:
Then run it with something like this (last 30 days in this example):