I am developing a tool which has a statistic page on which I am using HighCharts, I am using the basic line chart, Now to populate this chart I need some data. The data comes from my DB.
I got a query which extracts a list of users assigned to a particular 'Manager', Now I want each name to appear a s different line.
But What happens is that all names appear under one line........
My code:
<?php
session_start();
class ManagerStats{
public function con()
{
require_once('connect.php');
$DB = new dbConnect();
return $DB->connect();
}
public function DontEvenKnow(){
if($_SESSION['user'] == 'manager1#gmail.com'){
$sql = "SELECT user_id, first_name FROM tbl_user WHERE user_team='bob'";
$query = mysqli_query($this->con(), $sql);
if($query){
foreach($query as $v){
echo $v;
}
}
}elseif($_SESSION['user'] == 'manager2#gmail.com'){
//$sql = "SELECT user_id FROM tbl_user WHERE user_team='oli'";
}
}
}
?>
<script>
$(function () {
$('#home_manager').highcharts({
title: {
text: '',
x: -20 //center
},
xAxis: {
categories: ['04/19', '04/20', '04/21', '04/22', '04/23', '04/24']
},
yAxis: {
title: {
text: 'Emails Sent'
},
plotLines: [
{
value: 0,
width: 1,
color: '#808080'
}
]
},
tooltip: {
valueSuffix: ''
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [
{
name: '<?php $oko = new ManagerStats(); $oko->DontEvenKnow(); ?>',
data: [38, 78, 12, 80, 75]
},
{
name: 'Helena',
data: [23, 34, 55, 67, 34]
},
{
name: 'Martin',
data: [34, 35, 55, 69, 67]
},
{
name: 'Marta',
data: [43, 64, 75, 57, 64]
},
{
name: 'Samuel',
data: [63, 64, 75, 87, 44]
},
{
name: 'Carter',
data: [43, 54, 55, 67, 84]
}
]
});
});
</script>
In your function :
$data = "";
$data_for_user = "[43, 54, 55, 67, 84]";
//For each user you need to get data from database,
//but don't do a query inside a loop because it kills perfomance
foreach($query as $v){
$data .= " {
name: '".$v["first_name" ]."',
data: ".$data_for_user."
}, ";
}
echo $data;
then in series
series: [<?php $oko = new ManagerStats(); $oko->DontEvenKnow(); ?>]
This will do a new line on highcharts foreach user that you have
UPDATE: was missing one of the quotes on the array that might be why it wasn't working for the person if they just copied it.
UPDATE:
Getting data for more users for highcharts
You need a query with users and all his values that have to be in the graph:
$query = "SELECT t.user_id, t.first_name, group_concat( v.values ) as data_for_user
FROM tbl_user t,tbl_values v
WHERE t.user_id = v.user_id
GROUP by t.user_id";
Group concat get the values for user separated by comma the way you need for highcharts.
Remember that group_concat have a lenght limit of 1024 but you can change it with this before your query.
'SET GLOBAL group_concat_max_len=15000'
And data for highcharts
$data = "";
foreach($query as $v){
$data .= " {
name: '".$v["first_name" ]."',
data: [".$v["data_for_user"]."]
}, ";
}
Try adding a line break after you echo out the variable. Something like this:
echo $v . "<br />";
That should create a new line after each user.
Related
I am trying to plot a chart using Chart.JS with data from multiple MySql queries. However, when I tried loading it, the graph only display one month. Any idea how I can do this? Thank you. Hope you can help me
Here's the code for the queries:
//Query for graph
$applied_query = mysqli_query($link, "SELECT count(id) as 'count', monthname(date_created) as 'month' FROM data.application WHERE status ='APPLIED' AND year(date_created)= year(curdate()) GROUP BY month");
while ($row = mysqli_fetch_array($applied_query)){
$month[] = $row["month"];
$countApplied = $row['count'];
}
$verified_query = mysqli_query($link, "SELECT count(id) as 'count', monthname(date_verified) as 'month' FROM data.application WHERE status ='VERIFIED' AND year(date_verified)= year(curdate()) GROUP BY month");
while ($row = mysqli_fetch_array($verified_query)){
$month[] = $row["month"];
$countVerified = $row['count'];
}
$approved_query = mysqli_query($link, "SELECT count(id) as 'count', monthname(date_approved) as 'month' FROM data.application WHERE status ='APPROVED' AND year(date_approved)= year(curdate()) GROUP BY month");
while ($row = mysqli_fetch_array($approved_query)){
$month[] = $row["month"];
$countApproved = $row['count'];
}
$released_query = mysqli_query($link, "SELECT count(id) as 'count', monthname(date_released) as 'month' FROM data.application WHERE status ='RELEASED' AND year(date_released)= year(curdate()) GROUP BY month");
while ($row = mysqli_fetch_array($released_query)){
$month[] = $row["month"];
$countReleased = $row['count'];
}
And here's the code for the graph.
<!-- Bar Chart -->
<canvas id="barChart" style="max-height: 400px;"></canvas>
<script>
document.addEventListener("DOMContentLoaded", () => {
new Chart(document.querySelector('#barChart'), {
type: 'bar',
data: {
labels: <?php echo json_encode($month); ?>,
datasets: [{
label: 'Applied',
data: <?php echo json_encode($countApplied); ?>,
backgroundColor: [
'rgba(201, 203, 207, 0.3)'
],
borderColor: [
'rgb(201, 203, 207)'
],
borderWidth: 1,
}, {
label: 'Verified',
data: <?php echo json_encode($countVerified); ?>,
backgroundColor: [
'rgba(54, 162, 235, 0.3)'
],
borderColor: [
'rgb(54, 162, 235)'
],
borderWidth: 1
}, {
label: 'Approved',
data: <?php echo json_encode($countApproved); ?>,
backgroundColor: [
'rgba(60, 179, 113, 0.3)'
],
borderColor: [
'rgb(60, 179, 113)'
],
borderWidth: 1
}, {
label: 'Released',
data: <?php echo json_encode($countReleased); ?>,
backgroundColor: [
'rgba(255, 159, 64, 0.3)'
],
borderColor: [
'rgb(255, 159, 64)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks:{
beginAtZero: true
}
}]
}
}
});
});
</script>
<!-- End Bar CHart -->
The output should look like .
save your data to array like $month, example $countApplied = $row['count'] change to $countApplied[] = $row['count'];
while ($row = mysqli_fetch_array($applied_query)){
$month[] = $row["month"];
$countApplied[] = $row['count'];
}
My head is going to blow.
livedata.php loads json when page open.
live.php add point to graph.
From livedata.php i got output like this:
[["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37]]
live.php output - only last row, looks like
["Date.UTC('.2016, 07-1, 29, 15, 40.')", 44]
I've got chart, live addPoint working, but no date on x-axis. What i do wrong?
JS
var chart;
function requestData() {
$.ajax({
url: 'live.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 120; // shift if the series is
chart.series[0].addPoint(eval(point));
setTimeout(requestData, 10000);
},
cache: false
});
}
$(function () {
$.ajax({
url: 'livedata.php',
success: function(point) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'areaspline',
events: {
load: requestData
}
},
title: {
text: 'Revenue vs. Overhead',
},
subtitle: {
text: '',
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Amount'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
series: [{
name: 'Random data',
data: eval(point )
}]
});
},
});
});
live.php
global $dbConnection;
$stmt = $dbConnection->query('SELECT DATE_FORMAT(data,"%Y-%m-%d %H:%i") as dataa, humidity FROM sensorsdata order by id desc limit 1');
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = "Date.UTC('.$date_raw.')";
$ar = array($date_complete, $row[humidity]);
echo json_encode($ar, JSON_NUMERIC_CHECK);
livedata.php
global $dbConnection;
$stmt = $dbConnection->query('SELECT DATE_FORMAT(data,"%Y-%m-%d %H:%i") as dataa, humidity FROM sensorsdata');
$result = $stmt->fetchAll();
foreach ($result as $row) {
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = 'Date.UTC('.$date_raw.')';
$hum_for_chart[] = [$date_complete, $row[humidity]];
}
echo json_encode($hum_for_chart, JSON_NUMERIC_CHECK);
Chart:
Chart
I think its problem of your data try to make string like,
live.php
....
$date_complete = "Date.UTC('.$date_raw.')";
$ar = "[".$date_complete.",". $row[humidity]."]";
echo json_encode($ar);
livedata.php
....
foreach ($result as $row) {
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = 'Date.UTC('.$date_raw.')';
$hum_for_chart[] = "[".$date_complete.",". $row[humidity]."]";
}
....
You can refer highcharts-data-series-issue-with-ajax-json-and-php
i've got it! 2 days of mind blowing ))))
Thanks to Rohan Kumar for link.
I made changes from date.utc to unix timestamp.
$datetimeUTC = ((strtotime($row[dataa])+ 10800) * 1000);
$data[] = [$datetimeUTC, $row[humidity]];
echo json_encode($data);
10800 - that is +3 hours (Moscow timezone)
The output is
[[1469718529000,37],[1469718529000,37],[1469718530000,37],[1469718531000,37]]
And that's it, date axis started working!
Hi guys i need help with Highcharts library, i have this array coming from php,
[{"name":"25% en cambio de aceite 76 lubricants","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3]]},{"name":"10% Descuento en filtro de aceite","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3],["2015-10-03",3],["2015-10-05",1],["2015-10-09",1],["2015-10-10",1]]}]
I need to show this as line chart dynamically, but have been unable to do it, i believe the error comes from the quotes in dates, needs to be in format [Date.UTC(2015, 2, 6), 3]
This is my php function that returns the json data
public function actionTransactionsRedeemed() {
// Transacciones Totales redimidas por merchant
$sql = "SELECT DISTINCT `transaction`.idPromotion, promotion.`name` FROM `transaction` INNER JOIN promotion ON `transaction`.idPromotion = promotion.idPromotion WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion IS NOT NULL";
$idPromotion = Yii::app()->db->createCommand($sql)->queryAll();
$idPromotions = array();
$tempArray = array();
$result = array();
$i = 1;
$rs = array();
foreach($idPromotion as $i){
//process each item here
$id = $i["idPromotion"];
$tempArray['name'] = $i["name"];
$sql = "SELECT count(*) AS count, DATE(`transaction`.date) AS `date` FROM `transaction` WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion = $id GROUP BY DATE(`transaction`.date)";
$transactionsRedeemed = Yii::app()->db->createCommand($sql)->queryAll();
foreach($transactionsRedeemed as $item2){
$rs[0] = $item2['date'];
$rs[1] = $item2['count'];
$tempArray['data'][] = $rs;
$rs = array();
}
$i++;
array_push($result, $tempArray);
}
//$result = json_encode($result, JSON_NUMERIC_CHECK);
//echo json_decode($result);
print json_encode($result, JSON_NUMERIC_CHECK);
}
And this is the Jquery that builds the chart
$(document).ready(function() {
var options = {
chart: {
type: 'spline',
renderTo: 'chart-merchant-day',
defaultSeriesType: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Total de promociones redimidas',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%l%p', this.value);
}
}
},
yAxis: {
title: {
text: 'Transacciones'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%l%p', this.x-(24000*3600)) +'-'+ Highcharts.dateFormat('%l%p', this.x) +': <b>'+ this.y + '</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Count'
}],
credits: false
}
// Load data asynchronously using jQuery. On success, add the data
// to the options and initiate the chart.
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var lines = [];
traffic = [];
var data = $.parseJSON(tsv);
var x = 0;
//console.log(tsv);
$.each(data, function(i, item) {
//alert(item);
//console.log(item);
$.each(item, function(y, item2) {
if(y == "data"){
//console.log(item2);
try {
tsv = item2;
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
options.series[x].data.push([Date.parse(line[0]),line[1]]);
/*date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);*/
});
} catch (e) { }
options.series[x].data = traffic;
} else if(y == "name"){
options.series[x].name = item2;
}
});
x++;
});
chart = new Highcharts.Chart(options);
//console.log(tsv.replace(/\"/g, ""));
//tsv = tsv.replace(/\"/g, "");
});
});
Any help will be greatly appreciated, im so exhausted at this point.
The function is actually simpler,
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var data = $.parseJSON(tsv);
$.each(data, function (i, item) {
options.series.push({
name: item['name'],
data: []
});
$.each(item['data'], function (j, dataitem) {
var dataitemvalue = null;
try {
dataitemvalue = [Date.parse(dataitem[0]), dataitem[1]];
} catch (e) {}
options.series[i].data.push(dataitemvalue);
});
});
chart = new Highcharts.Chart(options);
});
JSFiddle demo
I have a json data that will retrive the selected data from database based on user checked on checkboxes. but I know my json data is not correct. Tried many way, but still wont works. This is the code:
<?php
foreach ($_GET['iddoc'] as $iddoc) //iddoc is the value of checked checkbox
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while ($r = mysql_fetch_assoc($sql_query))
{
$series1['name'][] = $r['subject'];
$series1['data'][] = $r['result'];
}
$jsonTable = json_encode($series1, JSON_NUMERIC_CHECK);
echo $jsonTable;
}
Based from the code below, lets say if I checked 3 checkbox (BAT123, BIO222, HIS TEST),The json output will be like this:
{"name":["BAT123"],"data":[3.03]}
{"name":["BAT123","BIO222"],"data":[3.03,1.05]}
{"name":["BAT123","BIO222","his test"],"data":[3.03,1.05,3.03]}
I know the json above was wrong, So how to make the json data will be display like this:
[
{"name":["BAT123"],"data":[3.03]},
{"name":["BIO222"],"data":[1.05]},
{"name":["his test"],"data":[3.03]}
]
This is my highcharts javascript code:
<script type="text/javascript">
$(function () {
var data = [
<?php echo $jsonTable; ?>
];
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'SamHistogramDiv',
type: 'column',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'SAM Histogram Results',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Percentage'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: data[0]
});
});
});
Thank u very much for your time..
Problem was with the json data format. It should be like
var data = [{name:"BAT123",data:[3.03]},{name:"BIO222",data:[1.05]},{name:"his test",data:[3.03]}];
foreach ($_GET['iddoc'] as $iddoc) //iddoc is the value of checked checkbox
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while ($r = mysql_fetch_assoc($sql_query))
{
$series[] = array('name'=>$r['subject'],'data'=>array($r['result']));
}
}
$jsonTable = json_encode($series);
echo $jsonTable;
Pls check if you are getting the json string as mentioned above /* data */
Check this link
http://jsfiddle.net/highcharts/Sq3KL/2/
Try this
foreach ($_GET['iddoc'] as $iddoc) //iddoc is the value of checked checkbox
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while ($r = mysql_fetch_assoc($sql_query))
{
$series[] = array('name'=>$r['subject'],'data'=>$r['result']);
}
}
$jsonTable = json_encode($series);
echo $jsonTable;
the out put will be like
[{"name":"BAT123","data":"3.03"},{"name":"BIO222","data":"1.05"},{"name":"HIs test","data":"1.00"}]
This is my Table structure
Here is my code: <br/>
<?php
$result_journ = mysql_query("SELECT jour_id, journal FROM journals");
$count_result = mysql_num_rows($result_journ);
while ($row_sd = mysql_fetch_array($result_journ)) {
$data_sd = $row_sd['jour_id'];
$namee= $row_sd['journal'];
?>
<script type="text/javascript">
$(function () {
$('#container_journal').highcharts({
xAxis: {
categories: [<?php
$test_q = mysql_query("SELECT jour_id, year FROM journ_graph WHERE jour_id = '$data_sd'");
while($row_q = mysql_fetch_array($test_q)){
$year_q = $row_q['year'];
echo $year_q.',';
}?>
]
},
yAxis: {
title: {
text: 'Citations'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: '<?php echo $namee; ?>',
data: [<?php
$sql= "SELECT `citations`, `jour_id` FROM `journ_graph` WHERE `jour_id` = '$data_sd'";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
echo $cita = $row['citations'].',';
?>]
}]
});
});
</script>
<?php
}
?>
The Result:
This is the result I am getting.
The expected Result:
The while loop is getting only one row. What would be the problem? Please help.
The while loop is getting only one row. What would be the problem? Please help.
Update Result:
Checkbox select
You are reinitializing the highcharts on each iteration of first while. Try the following code:
<?php
$result_journ = mysql_query("SELECT jour_id, journal FROM journals");
$count_result = mysql_num_rows($result_journ);
$categories = "";
$cita = array();
$count=0;
while ($row_sd = mysql_fetch_array($result_journ))
{
$data_sd = $row_sd['jour_id'];
$cita[$count]['name'] = $row_sd['journal'];
$test_q = mysql_query("SELECT jour_id, year FROM journ_graph WHERE jour_id = '$data_sd'");
while ($row_q = mysql_fetch_array($test_q))
{
$year_q = $row_q['year'];
$categories .= $year_q . ',';
}
$sql = "SELECT `citations`, `jour_id` FROM `journ_graph` WHERE `jour_id` = '$data_sd'";
$result = mysql_query($sql);
// I have added this while block thinking that you might have more than one rows
while ($row = mysql_fetch_array($result))
{
$cita[$count]['data'][] = $row['citations'];
}
$count++;
}
?>
<script type="text/javascript">
$(function () {
$('#container_journal').highcharts({
xAxis: {
categories: [<?= $categories ?>]
},
yAxis: {
title: {
text: 'Citations'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: <?= json_encode($cita, JSON_NUMERIC_CHECK) ?>
});
});
</script>