Reputation: 67
I'm still very new to SQL and I've managed to grab the data I want using a query. I want to be able to select the sum of records on a day and I can access it from PHP using
<?php
$sql = $pdo->prepare("select count(*) from `Visits` where
date(`Date`)=date(date_sub(now(),interval 1 day))");
$sql->execute();
$result = $sql->fetch(PDO::FETCH_ASSOC);
echo $result['count(*)'];
?>;
The data returns yesterdays records. The problem is I want to be able to do this for a set number of days (last 7 and last 30), and don't see it as feasible to repeat the above code that many times.
Any help on tweaking the query to return a single array that I could grab all those values would be really helpful! It would be ideal if the array could take the value 'number of days ago' and return the amount of records on that day.
Edit: I still need it to return 0 for days that don't have no records.
Upvotes: 1
Views: 380
Reputation: 11
If you want a table with the results per day, you need to modify your SQL query to return a table with both the Day and Count for each day. For that include the date as another column and group your results by the day.
<?php
$last_days=7
$sql = $pdo->prepare("select count(*) as `count`,date(`Date`) as `day` from `Visits` where
date(`Date`) > date(date_sub(now(),interval ? day)) GROUP BY date(`Date`)");
$sql->execute(array($last_days));
while($result = $sql->fetch(PDO::FETCH_ASSOC)) {
echo $result['count']. " for day:" . $result['day']." <br>\n";
}
?>
Upvotes: 1
Reputation: 6540
You could try it with timestamps:
<?php
$last_days = 7;
$sql = $pdo->prepare("select count(*) as count from `Visits` where
UNIX_TIMESTAMP(`Date`) < UNIX_TIMESTAMP() AND UNIX_TIMESTAMP(`Date`) > UNIX_TIMESTAMP() - 60 * 60 * 24 * $last_days");
$sql->execute();
$result = $sql->fetch(PDO::FETCH_ASSOC);
echo $result['count'];
?>;
Upvotes: 1