I am looping through a table to get the total entries for each month and will then output the array to a chart. Creating the array and chart works…but I am struggling to get the totals for each month. I am not sure how to construct the loop. Here is what I have so far:
$sql = "SELECT YEAR(member_since) AS year, MONTH(member_since) AS month FROM
members WHERE member_since > DATE_SUB(NOW(), INTERVAL 1 YEAR) GROUP BY year,
month";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row){
if ($row['month'] == '1'){
$january_total += 1;
}
.....
}
$chart1 = array(
array('Month', 'Totals'),
array('Januray Total',$january),
..................
);
At the end I want totals per month according to the date member_since
"SELECT YEAR(member_since) AS year, MONTH(member_since) AS month FROM members WHERE member_since > DATE_SUB(NOW(), INTERVAL 1 YEAR) GROUP BY year, month"
This query should return exactly 1 row per month and year. That’s what GROUP BY is intended for. "SELECT YEAR(member_since) AS year, MONTH(member_since) AS month, COUNT(id) AS total FROM members WHERE member_since > DATE_SUB(NOW(), INTERVAL 1 YEAR) GROUP BY year, month"
Yes I am using mysql and I assume that there will be no leading zero.
The bar chart will give the total subscriptions per month for the current year. But I need to consider that there might not be any subscription or activity for some months.
Ok thanks the code is working and the chart displays correctly. I just have one more question:
Does INTERVAL 1 YEAR take todays month and go back 12 months? OR does it grab the rows from this years January. I assume it goes back exactly 12 months right…which means if I run the script middle of the year I should on display the last 6 months.
so for example the total for March is in $totals[3], and assuming you’re on PHP 7.x you could use $totals[3] ?? '0' to display the result for March, or 0 if there is no result for March.
Selecting a Year interval will mean the Month column potentially has a duplicate value - running this query today will pull records from October 4-31 of 2018, as well as October 1-4 of 2019.