Get sql values and put in chart.js - javascript

I have been trying to get values from sql and put it to chart.js.
What I have accomplished is getting the right query in displaying the right data.
I am using bar chart in chart.js to display how many people have birthdays in each month.
SELECT COUNT( * ) FROM person WHERE MONTH( birthday ) = 02 //02 = February
I have seen a solution online but it is not for bar chart. Nevertheless, I tried it.
PHP code:
include('config.php');
$months = array("january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december");
$monthvalues = array();
foreach ($months as $month) {
$monthvalues[$month] = 0;
}
$result = mysqli_query($conn, "SELECT birthday, count(*) FROM person group by birthday;");
while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
$monthvalues[$row[0]] = (int)$row[1];
}
print (json_encode($monthvalues));
JS code:
$(document).ready(function () {
new Chart($("#canvas_bar").get(0).getContext("2d")).Bar({
labels: [<?=json_encode($months);?>],
datasets: [{
fillColor: "#03586A", //rgba(151,187,205,0.5)
strokeColor: "#03586A", //rgba(151,187,205,0.8)
highlightFill: "#066477", //rgba(151,187,205,0.75)
highlightStroke: "#066477", //rgba(151,187,205,1)
data: [<?=json_encode(array_values($monthvalues));?>]
}]
}, {
tooltipFillColor: "rgba(51, 51, 51, 0.55)",
responsive: true,
barDatasetSpacing: 6,
barValueSpacing: 5
});
});
My code returns NaN.
How can I properly do it? Thank you so much for your help.

It looks like at least part of the problem is that you are nesting your label and data arrays when they should just be a single dimension. Remove the outer brackets from your json_encode calls:
var barChartData = {
labels: <?=json_encode($months);?>,
datasets: [
{
fillColor: "#03586A", //rgba(151,187,205,0.5)
strokeColor: "#03586A", //rgba(151,187,205,0.8)
highlightFill: "#066477", //rgba(151,187,205,0.75)
highlightStroke: "#066477", //rgba(151,187,205,1)
data: <?=json_encode(array_values($monthvalues));?>
}
]
};
I'm not sure about your MySQL table structure, but it might be better to just get the month name and the count:
"SELECT LOWER(MONTHNAME(birthday)), count(*) FROM person GROUP BY LOWER(MONTHNAME(birthday))"
That will give you output like:
april 53
august 8
december 4
february 75
march 56
may 2
november 13
october 1
september 11
You could update your PHP to give you a more structured output like:
$result = mysqli_query($conn, "SELECT birthday, count(*) FROM person group by birthday;");
$output = array();
while ($row = mysqli_fetch_assoc($result, MYSQL_NUM)) {
array_push($output, $row);
}
print (json_encode($output));
That will output [{ "january": 53 }, { "february": 23 }, ....etc], then your javascript would change to:
var barChartData = {
labels: <?=json_encode(array_keys($output));?>,
datasets: [
{
fillColor: "#03586A", //rgba(151,187,205,0.5)
strokeColor: "#03586A", //rgba(151,187,205,0.8)
highlightFill: "#066477", //rgba(151,187,205,0.75)
highlightStroke: "#066477", //rgba(151,187,205,1)
data: <?=json_encode(array_values($output));?>
}
]
};
http://codepen.io/anon/pen/obmKer

Related

How many people are registering in the day of the week

Hi i want to make a chart for my project using chatjs. I have a users table and when user registered my site the registered time is datetime format like this 2018-03-02 10:35:25 . I want to make it with this chat DEMO
I need to write a php code to reveal the graph, like:
$months = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
$monthvalues = array();
foreach ($months as $month) {
$monthvalues[$month] = 0;
}
$result = mysqli_query($db,"SELECT registerTime, count(*) FROM users group by WEEKDAY(registerTime)") or die(mysql_error($db));
while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
$monthvalues[$row[0]] = (int)$row[1];
}
and i am printing it like this
// Data
var data = {
labels: <?=json_encode($months);?>,
datasets: [{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: <?=json_encode(array_values($monthvalues));?>
}]
};
The query above gives me just one log report. I can not show it on the chart. I need an output that I can reflect on a weekly basis.
The problem is, I can not figure out how to do graphs with code. Could someone help me by giving an example in this matter please ?
the result should be data: [28, 48, 40, 19, 86, 27, 90] like this
january = 28, february = 48 , ...
If you want to return an array, you should use a GROUP BY, like this
SELECT COUNT(registerTime) as `count` FROM users WHERE DATE(registerTime) = CURDATE() GROUP BY MONTH(registerTime)
And you can add a month number in output to create labels
SELECT COUNT(registerTime) as `count`,MONTH(registerTime) as `month` FROM users WHERE DATE(registerTime) = CURDATE() GROUP BY MONTH(registerTime)

How to pass values dynamically in Script using php to produce graph

I am trying create a bar chart for the data in mysql using php. I use bootstrap template to create application. I have predefined barchart with static data. I wanna add the data from the database. I tried my best but could not find solution as I am beginner in Javascript. Please guide me to add data dynamically. The Script is below:
// Bar chart
var ctx = document.getElementById("mybarChart");
var mybarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: '# of Votes',
backgroundColor: "#26B99A",
data: [10, 20, 30, 40, 20, 10, 40]
}, {
label: '# of Votes',
backgroundColor: "#03586A",
data: [41, 56, 25, 48, 72, 34, 12]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<div class="x_content">
<canvas id="mybarChart"></canvas>
</div>
If I understand the environment, you have php-produced webpages.
If so I would:
Create a .php file
Write some php code to connect to the database and to retrieve an array with the data to be charted
Copy your JS code, wrapped in <script> </script> tags and also wrap it in a JS Function which you'll call later in the page
Inside your JS code, after datasets, write a php loop as this:
// Bar chart
var ctx = document.getElementById("mybarChart");
var mybarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
<?php
if (count($arrayOfData) > 0){
echo "label: '# of Votes',";
echo "backgroundColor: '#26B99A',";
echo "data: [";
$firstValue = true;
foreach ($arrayOfData as $dataValue) {
if ( ! $firstValue ) {
echo ", ".$dataValue;
} else {
$firstValue = false;
}
echo $dataValue;
}
echo "]";
} else {
//Decide what to do if you don't have data
}
?>
}]
}'
Write the rest of the HTML/PHP page.
Note that if you want more than 1 bar in your graph you have to also cycle through different data sets, not only through one as I showed above for simplicity.

Chart js doesn't show chart

i try to display only the example from chart js in a project i work on. Unfortunately i'm forced to use Chart Js 1.x.
I tried to implement the bar example from https://github.com/chartjs/Chart.js/blob/master/samples/bar/bar.html
It's a pretty easy example i guess but it isn't running :(
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.1.1/Chart.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="zeitsteuerungChart"></canvas>
var barChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: 'Dataset 1',
borderWidth: 1,
data: [
"1","1","1","1","1","1","1"
]
}, {
label: 'Dataset 2',
borderWidth: 1,
data: [
"1","1","1","1","1","1","1"
]
}]
};
window.onload = function() {
var ctx = document.getElementById("zeitsteuerungChart").getContext("2d");
var myBar = new Chart(ctx, {
type: 'bar',
data: barChartData
});
};
The Chart JS manipulate the
<canvas id="zeitsteuerungChart"></canvas>
element to
<canvas id="zeitsteuerungChart" width="300" height="150" style="width: 300px; height: 150px;"></canvas>
but thats pretty much it. No diagram shows up. No error in Console. I tried to use jQuery as well to select the canvas with
var ctx = $("#zeitsteuerungChart").get(0).getContext("2d");
but same effect! On other subpages of the project it's working pretty fine!
You are using chart js v2 syntax on v1.
for v1
var barChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: 'Dataset 1',
borderWidth: 1,
data: ["1","1","1","1","1","1","1"]
},
{
label: 'Dataset 2',
borderWidth: 1,
data: ["1","1","1","1","1","1","1"]
}]
};
window.onload = function() {
var ctx = document.getElementById("zeitsteuerungChart").getContext("2d");
var myBar = new Chart(ctx).Bar(barChartData, options);
};
you can view chart options (chart js v1) here or complete options here

How do I insert PHP variable inside jQuery/JavaScript bootstrap?

So this is my first attempt at using bootstrap i am trying to use "chart_filled_blue" in bootstrap but im having problems including my php results inside the jquery for bootstrap i would be thank full for any help or advice.
MY basic pdo select which grabs the views / date
$sth = $db->prepare("SELECT date, views FROM views_by_date");
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
I will limit the select so it will only grab the last 6 or 7 rows
So now my chart_filled_blue.js is this
"use strict";
$(document).ready(function(){
// Sample Data
var d1 = [[1262304000000, 0], [1264982400000, 500], [1267401600000, 700], [1270080000000, 1300], [1272672000000, 2600], [1275350400000, 1300], [1277942400000, 1700], [1280620800000, 1300], [1283299200000, 1500], [1285891200000, 2000], [1288569600000, 1500], [1291161600000, 1200]];
var data1 = [
{ label: "Total clicks", data: d1, color: App.getLayoutColorCode('blue') }
];
$.plot("#chart_filled_blue", data1, $.extend(true, {}, Plugins.getFlotDefaults(), {
xaxis: {
min: (new Date(2009, 12, 1)).getTime(),
max: (new Date(2010, 11, 2)).getTime(),
mode: "time",
tickSize: [1, "month"],
monthNames: ["Jan", "FebBBBB", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
tickLength: 0
},
series: {
lines: {
fill: true,
lineWidth: 1.5
},
points: {
show: true,
radius: 2.5,
lineWidth: 1.1
},
grow: { active: true, growings:[ { stepMode: "maximum" } ] }
},
grid: {
hoverable: true,
clickable: true
},
tooltip: true,
tooltipOpts: {
content: '%s: %y'
}
}));
});
I would like to replace all the var d1 with the views from the db and then the monthNames to the date from the db
What would the best way be to do this ?
You can replace d1 with <?php echo $result['view'];?>
You either insert the variable at build-time, e.g. you turn your JS script into a .php file and have:
...
var d1 = <?php echo json_encode($results_from_db); ?>;
...
Or you use an AJAX call to fetch the results from the server.
var d1;
$.get('fetchdata.php", {}, function(data) { d1 = data; });
If the d1 data you're fetching will never change for the life of the page, then insert it at page-build time. it'll save you having to fire off ANOTHER http request back to the server to fetch the data.
If the data does change periodically, then you can combine the methods. Use the PHP-only method to insert the "first draft" of the data, then use ajax to fetch the updates.
populate your database results in the beginning of the php page
$sth = $db->prepare("SELECT date, views FROM views_by_date");
$sth->execute();
$result = $sth->fetchAll();
$result = json_encode($result);
in javascript
var d1 = JSON.parse(<?php echo $result; ?>);

PHP MySQL: count views per month for jQuery charts

i work with jQuery chart.js for show view counter by month using PHP and MySql. I insert/Put each views page to MySql like this :
| id | ip | page | date(timestamp) |
| 1 | 138.86.20.20 | test.php | 1375710823 |
| 2 | 100.86.123.10 | test.php | 1380206563 |
for chart.js :
var data = {
labels: ["january","February", "March", "April", "May", "June", "July"],
datasets: [{
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,1)",
data: [150,59, 90, 81, 56, 55, 40]
}, {
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,1)",
data: [20,48, 40, 59, 500, 127, 100]
}]
}
var options = {animation :true};
//Get the context of the canvas element we want to select
var c = $('#daily-chart');
var ct = c.get(0).getContext('2d');
var ctx = document.getElementById("daily-chart").getContext("2d");
//Run function when window resizes
$(window).resize(respondCanvas);
function respondCanvas() {
c.attr('width', jQuery("#daily").width());
c.attr('height', jQuery("#daily").height());
//Call a function to redraw other content (texts, images etc)
myNewChart = new Chart(ct).Bar(data, options);
}
//Initial call
respondCanvas();
Now, I need to count views by/per month for chart.js data ouput using json format.
[150,59, 90, 81, 56, 55, 40,12,54,65,365,2] for 12 month strat #january.
How to crate this?!
NOTE: charts datasets have two color : 1- unique user 2- all user
You could use a query to group the visits by month:
SELECT COUNT(*), MONTH(date(timestamp)), YEAR(date(timestamp))
FROM table
GROUP BY MONTH(FROM_UNIXTIME(date(timestamp)), YEAR(FROM_UNIXTIME(date(timestamp))
Which will return the number of visits, with the year and month they correspond to.
\EDIT\
To loop through and print each month's value, use a mysqli_query and WHILE in PHP:
$query = mysqli_query($con, "THE QUERY ABOVE ^^");
while($row = mysqli_fetch_array($query {
echo $row['date(timestamp)'].",";
}

Categories

Resources