Reputation: 2866
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)?
Upvotes: 1
Views: 627
Reputation: 53319
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.
$query = mysql_query("SELECT type, count(*) FROM tracking WHERE htcode = '$htG' AND type IN ('viewed', 'shared', 'printed', 'emailed', 'used') AND date >= '$start_date' AND date <= '$end_date' GROUP BY type");
Here's just the query itself formatted over several lines for clarity:
SELECT type, count(*)
FROM tracking
WHERE htcode = '$htG'
AND type IN ('viewed', 'shared', 'printed', 'emailed', 'used')
AND date >= '$start_date' AND date <= '$end_date'
GROUP BY type
Just make sure you set the values for $start_date
and $end_date
first. For example, for today you'd just set them both to this:
$start_date = date('Y-m-d');
$end_date = date('Y-m-d');
Note that date('Y-m-d')
is just today's date in a format like YYYY-MM-DD
.
For yesterday, you'd pass in yesterday's timestamp into the date() function, but use the same format:
$start_date = date('Y-m-d', strtotime('yesterday'));
$end_date = date('Y-m-d', strtotime('yesterday'));
And for the past thirty days, you'd start 30 days ago and end today:
$start_date = date('Y-m-d', strtotime('30 days ago'));
$end_date = date('Y-m-d');
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:
function report_range($htG, $start_date, $end_date) {
$query = mysql_query("SELECT type, count(*) FROM tracking WHERE htcode = '$htG' AND type IN ('viewed', 'shared', 'printed', 'emailed', 'used') AND date >= '$start_date' AND date <= '$end_date' GROUP BY type");
while ($result = mysql_fetch_assoc($query)){
echo $start_date . '-' . $end_date . ' / ' . $result['type'] . ' = ' . $result['count(*)'];
echo '<br>';
}
}
Then run it with something like this (last 30 days in this example):
report_range($htG, date('Y-m-d', strtotime('30 days ago')), date('Y-m-d'));
Upvotes: 1