How many people are registering in the day of the week - javascript

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)

Related

Chart.js - get base 64 encoded string as variable

I'm creating a chart using the Chart.js library and it's working well. I'm using the .toBase64Image() function to generate a base 64 encoded string of the chart (png data url).
I can see this when I inspect the chart in my browser developer tools, e.g.:
data:image/png;base64,iVBORw0KGgoAAAA etc
I now need to call a URL to another application that will pass the data url as a parameter - I'm just stuck at how to get the data url as a parameter to pass to my URL that I will then call.
Here's my script as it currently stands:
var radarChartData = {
labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"],
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [3, 2, 1, 5, 6, 8, 5]
},
]
};
window.onload = function() {
window.myRadar = new Chart(document.getElementById("canvas").getContext("2d")).Radar(radarChartData, {
responsive: true,
scaleOverride: true,
scaleSteps: 10,
scaleStepWidth: 1,
scaleStartValue: 0,
onAnimationComplete: function() {
document.getElementById("canvas").innerHTML = myRadar.toBase64Image();
theURL = "fmp://$/chartingFile?script=getChartToContainer&param=";
window.location = theURL;
}
});
}
I need to append the "data:image/png;base64,iVBORw0KGgoAAAA" string to the 'theURL' variable but can't figure out how to get this as a string?
Managed to work this out as follows:
onAnimationComplete: function() {
document.getElementById("canvas").innerHTML = myRadar.toBase64Image();
var x = document.getElementById("canvas").innerHTML = myRadar.toBase64Image();
theParam = encodeURIComponent(x);
theURL = "fmp://$/chartingFile?script=getChartToContainer&param=" + theParam;
window.location = theURL;
Not sure if it's optimal etc but it's working well so far.

Looping inside variable (json data)

Anyone know how looping json data INSIDE varibale?? Example
var data = {
$.each(data, function(i, item) {
console.log(data[i].PageName);
});​
labels: [dateLoop],
datasets: [{
}]
};
Well that code is didnt work for me. I want looping inside that varibale. Anyway this coding for Chart.js
Why i need looping?? cuase i have filter buyer and date range, if i choose 3 buyer, and date range from january 2016 to May 2016. On data will show data buyer, each data buyer will have value from date range. Exmaple data json
data [Buyer 1] : ["167404", "129770", "113598", "127301", "156868", "634789", "242188", "166312", "169418"];
data [Buyer 2] : ["9580", "22250", "3500", "5558", "254556", "268500", "77750", "69850", "55"];
So what i need how too looping inside variable?? Sorry my bad languange.
Edit probbaly someone dont know what i mean,
example i have pick 2 buyer, Buyer A (Json["data"][0]) and Buyer B (Json["data"][1]) and each that buyer have value (wich this value order by month if i pick January and May, it will show "222","555")
and the code i mean like this :
var data = {
labels: [dateLoop], #ignore this
datasets: [{ label : (Json["data"][0])
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [(value orderby month in Json["data"][0]]
},
{ label : (Json["data"][1])
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [(value orderby month in Json["data"][1]]
}
]
};
That i want it. But i sue each make error. :/
try this, you need 2 loop first loop is for keys and second is for the values inside array
var data = {
'Buyer 1': ["167404", "129770", "113598", "127301", "156868", "634789", "242188", "166312", "169418"],
'Buyer 2': ["9580", "22250", "3500", "5558", "254556", "268500", "77750", "69850", "55"]
}
for(var key in data) {
for (var x in data[key]) {
console.log(data[key][x]);
}
}

Get sql values and put in chart.js

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

Chart.js custom tooltipTemplate index

I have this chart made with Chart.js.
var data = {
labels: ["", "", "", "2015-08-28", "2015-08-29", "2015-08-30", "2015-08-31", ],
websites: ["", "", "", "gamesoutletCrawler", "gamesoutletCrawler", "G2PLAY", "instantgaming", ],
datasets: [{
label: "Best price last 7 days",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [0, 0, 0, 34.5, 36.8, 37.3, 37.99, ]
}]
};
window.onload = function() {
var ctx = document.getElementById("chartkeys").getContext("2d");
window.myLine = new Chart(ctx).Line(data, {
responsive: true,
tooltipTemplate: "<%= data.websites[idx] %>",
scaleLabel: "<%= Number(value).toFixed(2).replace('.', ',') + ' €'%>"
});
}
On my tooltip template, I want to use values from data.websites but I don't know how to pass in the index for my tooltip array. This is not working:
<%= data.websites[idx] %>
idx is wrong, it's not the index the system is using. Any idea what I have to write here to show the index tooltip when you hover on the graph?
If I write <%= data.websites %>, it's showing me all the websites in the array, not the one hovered.
You can use a function instead of a template string
...
tooltipTemplate: function (d) {
return data.websites[data.labels.indexOf(d.label)]
},
...
Note that this requires the labels to be unique, or if there are duplicate labels that it not matter which one is active (for instance, in your data, the first 3 labels are the same but that won't cause any problems because the first 3 entries in the websites array too are the same. If they were different this method will not work)

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