How to properly display data in chartjs from SQL? - javascript

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
}
}
}
});

Related

Using PHP and Javascript in a hybrid way, to traverse through a loop

I am trying to draw two graphs using chartjs. I want to make my life simplier by using a for loop to declare the variables required for the chart object.
The thing is I have created a 2d array, with each row storing data for current year, the next row storing data for the consecutive year and so on. I am trying to access the row of the variable using loop.
Here is my Chart obj
var canvas6= {
type: 'doughnut',
data: {
datasets: [{
data: [
<?php
for($i=0;$i<count($dataAgeGrp[1]);$i++){ -------->Note here
echo $dataAgeGrp[1][$i]; -------->And here
echo ',';
}
?>
],
backgroundColor: [
<?php
for($i=0;$i<count($ageCategory);$i++){
$rand = str_pad(dechex(rand(0, 0xFFFF00)), 6, 0, STR_PAD_LEFT);
echo('"#' . $rand.'"');
echo ",";
}
?>
],
label: 'Pie Chart'
}],
labels: [
<?php
for($i=0;$i<count($ageCategory);$i++){
echo $ageCategory[$i];
echo ',';
}
?>
],
},
options: {
responsive: true
}
};
$(function () {
var ctx126 = document.getElementById('canvas6').getContext('2d');
window.myPie = new Chart(ctx126 , canvas6);
});
So, I tried something like this
for(var k=0;k<3;k++){
var q=26;
var canvas+q = {
type: 'doughnut',
data: {
datasets: [{
data: [
<?php
for($i=0;$i<count($dataAgeGrp[k]);$i++){
echo $dataAgeGrp[k][$i];
echo ',';
}
?>
],
backgroundColor: [
<?php
for($i=0;$i<count($ageCategory);$i++){
$rand = str_pad(dechex(rand(0, 0xFFFF00)), 6, 0, STR_PAD_LEFT);
echo('"#' . $rand.'"');
echo ",";
}
?>
],
label: 'Pie Chart'
}],
labels: [
<?php
for($i=0;$i<count($ageCategory);$i++){
echo $ageCategory[$i];
echo ',';
}
?>
],
},
options: {
responsive: true
}
};
$(function () {
var ctx1+q = document.getElementById('canvas'+q).getContext('2d');
window.myPie = new Chart(ctx1+q , canvas+q);
});
q=q+1;
But I am getting this error
Use of undefined constant k - assumed 'k' (this will throw an Error in a future version of PHP)
How do I fix it?
If you can use PHP variables in your JavaScript code, the contrary is not possible. The only way to pass JavaScript variable to PHP code is by request (reload page with GET/POST parameters or AJAX request)

PHP Array seen as single element in Chartjs

I have two arrays in PHP which I am trying to pass to a Chart to be displayed in Chartjs.
The following code creates the arrays by using a foreach on a multidimensional array to extract them.
<?php
$behaviours = orderByType($_SESSION['loggedStudent']['studentID']);
$behTypes = array();
$behValues = array();
foreach($behaviours as $item){
$behTypes[] = $item["type"];
$behValues[] = intval($item["count(*)"]);
}
// php arrays to JSON
$behaviourLabels = json_encode($behTypes, TRUE);
$behaviourValues = json_encode($behValues, TRUE);
?>
<canvas id="pie-chart" width="800" height="450"></canvas>
<script>
// parse to js
var strLables = <?php echo($behaviourLabels); ?>;
var strValues = <?php echo($behaviourValues); ?>;
// parse as array
var arrLables = JSON.parse($strLables);
var arrValues = JSON.parse($strValues);
new Chart(document.getElementById("pie-chart"), {
type: 'pie',
data: {
labels: arrLabels,
datasets: [{
label: "Incident Type",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: arrValues,
}]
},
options: {
title: {
display: true,
text: 'Breakdown of incident types for <?php echo($_SESSION['loggedStudent']['firstName']); ?>'
}
}
});
</script>
No chart or labels are showing. What am I doing wrong?
The expected values for both data and labels are array.
What you need to do is pass json to JavaScript.
// php arrays to JSON
$behaviourLabels = json_encode($behTypes);
$behaviourValues = json_encode($behValues);
Now in javascript
var arrLables = <?php echo($behaviourLabels); ?>;
var arrValues = <?php echo($behaviourValues); ?>;
// Now use them directly in you configuration
data: {
labels: arrLables,
datasets: [{
label: "Incident Type",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: arrValues,
}]
},

3d interactive pie chart offline

I want to constract a 3d interactive pie chart. Firstly I use google charts but unfortunately this doesn't work offline. I used charts from jpgraph, jscharts and rgraph but doesn't have the effect that I want. I want a graph which must be free, work offline and has approximately the same appearance with google graph. Any advice?
Thanks in advance!
Important I want to use results from my db. I write this code but dont work:
data: [{
name: 'Present',
y: <?php
while( $row2 = mysql_fetch_assoc($res2)){
echo $row2["COUNT(*)"];
}
}, {
name: 'absentees',
y: <?php
while( $row1 = mysql_fetch_assoc($res1)){
echo $row1["COUNT(*)"];
}
I have those queries:
SELECT COUNT(*)
FROM staff s, work w, absence a
WHERE s.id=a.id_staff
AND s.id_work=w.id
AND w.name='sales manager'
AND a.name='disease'
SELECT COUNT(*)
FROM staff s, work w, absence a
WHERE s.id=a.id_staff
AND s.id_work=w.id
AND w.name='sales manager'
AND a.name='vacation'
I try this but doesnt work
series: [{
type: 'pie',
name: 'Absent',
data: [
['Absent Illness', <?php
while( $row1 = mysql_fetch_assoc($res1)){
while( $row2 = mysql_fetch_assoc($res2)){
$row['COUNT(*)']=$row2['COUNT(*)'] - $row1['COUNT(*)'];
echo $row["COUNT(*)"];
}
}
?>],
['Absent Vacation',
<?php
while( $row1 = mysql_fetch_assoc($res1)){
echo $row1["COUNT(*)"];
}
?>]
]
}]
});
Please use highchart because it provide the varrious type of charts and you can also use it offline mode also. https://www.highcharts.com/
Let me guide to display mysql results onto the pie chart.
function functionname() {
$.ajax({
url : 'POST API LINK',
type : 'GET',
dataType : 'json',
success : function(data) {
var chart = new CanvasJS.Chart("chartContainer", {
title : {
text : "A suitable title"
},
animationEnabled : true,
zoomEnabled : false,
data : [ {
type : "pie",
dataPoints : [ {
y : data.active,
indexLabel : "Active part=" + data.active
}, {
y : data.Inactive,
indexLabel : "Inactive part=" + data.Inactive
},
]
} ]
});
chart.render();
},
error : function() {
alert('sorry!Somthing went wrong in Pie chart');
}
});
}
This is how you display MySQL results.
Here In data,I am getting active and inactive value from my DB.
For the UI, Please check this fiddle link.
Kindly let me know if you have any queries.

Get data highchart from php table

i want to show every row data from my table to highchart, how can i show that data using php to javascript foreach row?
<script>
series: [{
name: 'Mie Instan',
data: [<?php foreach ($query as $row){echo $row['mie'];}]
}, {
name: 'Beras',
data: [<?php foreach ($query as $row){echo $row['beras'];}]
}, {
name: 'Telur',
data: [<?php foreach ($query as $row){echo $row['telur'];}]
}]
</script>
What I would do, in order to get the HighCharts data arranged as an array of numerical values, is to use php array_push and PHP foreach to sort the data in three different PHP arrays.
<?php
// Declare 3 new arrays.
$mie=[];
$beras=[];
$telur=[];
// Fill the arrays with the database values
foreach ($query as $row){
array_push($mie, $row['mie']);
array_push($beras, $row['beras']);
array_push($telur, $row['telur']);
}
?>
Then use the arrays to produce a string of "coma separated values" in the HighCharts script, using PHP join, like this:
<script>
series: [{
name: 'Mie Instan',
data: [<?php echo join(",", $mie); ?>]
}, {
name: 'Beras',
data: [<?php echo join(",", $beras); ?>]
}, {
name: 'Telur',
data: [<?php echo join(",", $telur); ?>]
}]
</script>
Hoping this helps...
;)

JSON data not showing in highstock Candlestick chart using PHP & MYSQL

I'm trying to create a highstock's candlestick chart using php and mySQL.
this is my code so far, really appreciate if anyone can help me with this:
This my code for retrieving data from mySQL database and convert it to JSON format (datachart.php):
$conn = mysql_connect("localhost", "root", "") or die (mysql_error ());
$db = mysql_select_db ("b27sim") or die (mysql_error ());
$result=mysql_query ("SELECT date, open, high, low, close FROM mb27_daily") or die (mysql_error ());
$data = array();
$count = 0;
while ($row=mysql_fetch_array($result))
{
$newdate = strtotime($row['date']) * 1000;
$data[] = array( $newdate, (float)$row['open'], (float)$row['high'], (float)$row['low'], (float)$row['close']);
$count++;
}
echo json_encode($data);
This is the result from datachart.php:
[[1350252000000,369.72,371.02,368.09,370.22],[1349820000000,366.58,369.13,364.92,368.92],[1349733600000,367.38,369.93,366.82,368.64],[1349388000000,367.28,371.85,367.2,369.9],[1349301600000,362.75,366.24,362.22,365.61],[1349215200000,363.34,363.54,361.27,362.27],[1349128800000,360.79,362.73,360.33,361.77],[1349042400000,360.75,360.75,357.94,359.46],[1348783200000,360.62,362.69,359.84,362.5],[1348696800000,356.39,361.01,355.32,359.34],[1348524000000,358,360.39,356.34,359.7],[1348437600000,357.96,360.99,355.92,356.89],[1348178400000,359.27,360.53,356.93,360.53],[1348092000000,358.74,359.31,356.51,358.01],[1348005600000,357.97,361.82,357.24,359.86],[1347919200000,359.8,360.34,356.78,358.5],[1233010800000,119.28,122.42,119.28,121.91]]
And this is my javascript code inside index.htm:
$(function() {
$.getJSON('datachart.php', function(data) {
// create the chart
chart = new Highcharts.StockChart({
chart : {
renderTo : 'container',
},
rangeSelector : {
selected : 1
},
title : {
text : 'IB27 Price'
},
series : [{
type : 'candlestick',
name : '',
data : data,
tooltip: {
valueDecimals: 2
},
dataGrouping : {
units : [
['week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]]
]
}
}]
});
});
});
and this is my div calling the container:
<div id="container" style="height: 500px; min-width: 500px"></div>
and this is the result:
I got has not graph inside, but showing the timeline at the bottom, the date range on right top, etc.
Appreciate you guys help on this as I've been banging my head for the last 4 hours because of this... :)
Thanks,
Raz
Your data should be sorted by x (timestamps), ascending.

Categories