I got started with chartJS, so I really need guidance of where to look and learn. I’m trying to display duplicated data from my SQL to chartJS.
Example:
Table name: Traffic Violations
Data I want to display: Violation types (Speeding, drifting, seatbelt, etc).
How it should be displayed: Y-axis as numbers, X-axis as violation names.
I read this: SQL count how many duplicated values of a derived table
Watched this: 1.3: Graphing with Chart.js – Working With Data & APIs in JavaScript
also watched this: How to Switch Chart to Daily, Weekly and Monthly Data in Chart js
And this: Count Total number of rows in database in php -Analytics in php
I learned few things from each, but still didn’t satisfy my knowledge needs to achieve the goal I want.
I want to display the data in “Daily”, “Monthly”, “Yearly” format.
Sounds like that’s a totally different topic, because I want the “daily” chart to reset every 24 hours, and monthly every month without deleting the data from DB. None of these videos above shows me that, nor I couldn’t find what I’m looking for..
So, how to prepare my DB for chartJS?
best practice to fetch data and show it in the chart?
Here is what I have so far:
<?php
header('Content-Type: application/json');
require_once('./backend/config/connection.php');
$sqlQuery = "SELECT violationType, count(*) AS duplicates FROM traffic_violations GROUP BY violationType ORDER BY duplicates DESC";
$statement = $connection->prepare($sqlQuery);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
if ($row->num_rows > 0)
{
// output data of each row
while($row = $row->fetch_assoc())
{
echo $row["duplicates"]. "<br>";
}
}
else
{
}
echo json_encode($data);
?>
Chart:
const ctx = document.getElementById('chart-test').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Speeding', 'Drifting', 'Sealtbelt', 'Wrong Parking', 'Wrong Lane Drive', 'No License'],
datasets: [{
label: 'Traffic Violations',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ['rgba(255, 99, 132)'],
borderColor: ['rgba(255, 99, 132)'],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});