I’m working on a project to show how many birthdays happen each month using a bar chart. I’ve got the SQL query working fine:
SELECT COUNT(*) FROM employees WHERE MONTH(birth_date) = 1
But I’m stuck on how to get this data into Chart.js. I tried something like this:
$months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
$birthday_counts = [];
foreach ($months as $index => $month) {
$query = $db->query('SELECT COUNT(*) FROM employees WHERE MONTH(birth_date) = ' . ($index + 1));
$birthday_counts[] = $query->fetchColumn();
}
$chart_data = json_encode($birthday_counts);
And then in my JavaScript:
let ctx = document.getElementById('birthdayChart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [{
label: 'Birthdays per Month',
data: JSON.parse(chartData),
backgroundColor: 'rgba(75, 192, 192, 0.6)'
}]
}
});
But it’s not working right. The chart shows up empty. What am I doing wrong? How can I fix this to show the birthday data correctly in the bar chart?