PHP MySQL: count views per month for jQuery charts - javascript

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)'].",";
}

Related

Show analytics of registered users for last 12 months using chart

I'm trying to get all users for the last 12 months from database and show some statistics using chart.For that purpose I'm using chartJS.
$registeredUsersData = $connection->fetchAll(
'SELECT
COUNT(id) AS registered_users,
CONCAT(MONTHNAME(created_on), " ", YEAR(created_on)) AS created_on
FROM users
WHERE created_on
BETWEEN CURDATE() - INTERVAL 12 MONTH AND CURDATE()
GROUP BY YEAR(created_on), MONTH(created_on)
ORDER BY YEAR(created_on) DESC, MONTH(created_on) DESC;
');
We pass it by symfony controller and render html template.
$registeredUsersCount = array_column($registeredUsersData, 'registered_users');
$registeredUserMonths = array_column($registeredUsersData, 'created_on');
return $this->render('dashboard/admin/index.html.twig', [
'registered_users_count' => $registeredUsersCount,
'registered_users_months' => $registeredUserMonths
]);
In the template I'm trying to display using a bar diagram that data where year and month should be combined and display on the abscissa(X-axis) and the count respectively on the ordinate(Y-axis).
<div class="chart-container">
<canvas id="canvas"></canvas>
</div>
let months = {{ registered_users_months|json_encode|raw }};
let users = {{ registered_users_count|json_encode|raw }};
const ctx = document.getElementById('canvas').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: months,
datasets: [{
label: 'Registered Users Monthly',
data: users,
backgroundColor: 'rgba(90, 80, 191, 0.2)',
borderColor: 'rgba(90, 80, 191, 1)',
borderWidth: 1
}]
},
options: {
maintainAspectRatio: false,
responsive: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
},
}]
}
}
});
Data is properly displayed but not all "previous" 12 months are displayed.If a month does not have registered users it must be displayed as well but with count of zero. Unfortunately, the given query does not support that function currently, how could I modify it?
You need to make changes in your query like below:
$start = new DateTime(date('Y-m-d'));
$end = new DateTime(date('Y-m-d'));
$end->modify('+12 month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
$registeredUsersData[$dt->format('Y-m')] = 0;
}
$registeredUsersData = $connection->fetchAll(
'SELECT
COUNT(id) AS registered_users,
DATE_FORMAT(created_on,'%Y-%m') AS created_on
FROM users
WHERE created_on BETWEEN CURDATE() - INTERVAL 12 MONTH AND CURDATE()
GROUP BY DATE_FORMAT(created_on,'%Y-%m')
ORDER BY DATE_FORMAT(created_on,'%Y-%m') DESC;
');
foreach($registeredUsersData as $registeredUser) {
$registeredUsersData[$registeredUser['created_on']] = $registeredUser['registered_users'];
}
return $this->render('dashboard/admin/index.html.twig', [
'registered_users_count' => array_values($registeredUsersData),
'registered_users_months' => array_keys($registeredUsersData)
]);
I also updated your PHP have all dates for 12 months
I am more of a caveman coder than eloquent, but I believe this gets the result set you are looking for without changing your query... add this after your query to send the new data set to your controller.
for ($i = 1; $i < 12; $i++) {
$monthToCheck[$i]['registered_users'] = 0;
$monthToCheck[$i]['month_of_creation'] = date("F", strtotime( date( 'Y-m-01' )." -$i months"));
$monthToCheck[$i]['year_of_creation'] = date("Y", strtotime( date( 'Y-m-01' )." -$i months"));
}
return (array_merge($registeredUsersData,$monthToCheck));

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)

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

Bar graph from json response using Jquery

I have an AJAX call which on success gets a JSON response in the below format. Where the number of JSON array columns does not change but the number of entries can increase. Need help in plotting this as a bar chart using jQuery.
[
{
"amount": XX,
"instanceId": "XXX",
"timeStamp": XXX
},
{
"amount": XX,
"instanceId": "XX",
"timeStamp": XX
}
]
You should show code of what you have tried so far and ask a specific question about an issue you are having. Without this information it's hard to provide a suitable answer. That being said, I will provide one way of creating a dynamic bar chart with JavaScript.
This approach uses Chart.js which is a responsive HTML5 charting library that uses the <canvas> element. They provide a bar chart implementation and you can find the documentation for it here.. The first thing to do is include the library into your HTML file (download it and put it in a directory on your server first):
<script src="Chart.js"></script>
Then, in your HTML add a canvas element where the chart will be displayed:
<canvas id="myChart" width="400" height="400"></canvas>
Now, in your JavaScript file, create the chart object using the canvas context:
var ctx = document.getElementById("myChart").getContext("2d");
var chartObject = new Chart(ctx);
Then, using the chart object we created, we can call the Bar(data, options) factory method on it to create the bar chart. The Bar() method takes two arguments: a data object and a options object. The options object allows you to alter certain default functionality. The data object is where you will add your values retrieved from your AJAX call.
The data object contains two direct properties: labels and datasets; each of which are arrays. The labels will be what displays on the bottom of the graph going horizontally, such as dates. Each object in the datasets array will contain a data property which will be the y-value of that particular bar graph corresponding to the label at the same index. They may sound confusing but it's really not once you have a look:
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
Where the first index of both objects data arrays will correspond to the first index in the label array: bar one was at 65 in January and bar two was at 28 in January.
Since now we have our data object, we can now create the bar graph:
var barChart = chartObject.Bar(data);
Now, whenever you get more data you can add it with the following method:
// The values array passed into addData should be one for each dataset in the chart
barChart.addData([40, 60], "August");
// The new data will now animate at the end of the chart.
And you can even add more datasets:
barChart.datasets.push("data to push");
That should give you enough of a start. You just need to provide some alterations to fit your scenario.

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

Categories

Resources