flot chart populating xaxis with array - php

im trying to populate my xaxis using only data stored in the array $date[]
this is my coding;
<?php
// Main query to pull data from 'tests' table
$sql = "SELECT UNIX_TIMESTAMP(`date`)*1000 AS unixDate,`date`, `test1`, `test2`, `test3`, `test4`, `test5`, `test6`, `test7`, `test8`, `test9`, `test10`, `test11`, `test12`, `test13`, `test14` FROM `tests` WHERE member_id = '1' ORDER by `date` ASC";
$result = mysql_query($sql) or die ("no query");
// Dataset#1
while($row = mysql_fetch_assoc( $result )) {
$dataset1[] = array( $row['unixDate'], sprintf( "%.3f", $row['test1'] ));
$date[] = array($row['unixDate']);
}
?>
<div id="chart1Canvas" style="width:510px;height:200px;">
<div id="chart1" style="width:500px;height:200px;"></div></div>
<script type="text/javascript">
//START CHART#1
var dateArray = [ <?php echo json_encode($date); ?> ];
var chart1Options = {
xaxis: {show: true, mode: "time", timeformat: "%y-%m-%d", ticks: dateArray},
yaxis: {show: true, min: 1.000, max: 1.050, tickDecimals: 3 },
lines: {
show: true,
fill: true,
fillColor: { colors: [{ opacity: 0.2 }, { opacity: 0.2}] }
},
points: { show: true, radius: 1 },
grid: {
show: true,
color: '#fff',
backgroundColor: false,
borderWidth: 0,
hoverable: true,
clickable: true }
};
function getTooltip(label, x, y) {
return "Your sales for " + x + " was $" + y; }
var dataset1 = { data: <?php echo json_encode($dataset1); ?>, color: 'white'};
$.plot($("#chart1"), [ dataset1 ], chart1Options);
//END CHART#1
</script>
when i run this my entire xaxis dissapears, i assumed i have to JSON_encode the date[] array before assigning it to the 'ticks' option for my xaxis?
can someone check what i have done wrong here?
thank you.
edit: changed something and now its doing something, but still no grid and labels for xaxis?
check link: http://www.myreeftests.com/graphs2.php

Your dateArray looks like this:
var dateArray = [ [["1367704800000"],["1367791200000"], ...
but it has to look like this:
var dateArray = [1367704800000,1367791200000, ...
So remove the outer [ ] in the javascript and format the timestamps as longint instead of as arrays of a string (not sure how to do that in php).
See the documentation for more information.

ok so with messing around i managed to get it to show the correct ticks using an array, last problem is formating the ticks to space out evenly;
[link]http://www.myreeftests.com/graphs2.php

Related

highcharts does not seem to be rendering

I am following this example
https://www.highcharts.com/docs/chart-and-series-types/pie-chart
I want to display highcharts through retrieving data from the database. My pie highcharts is not displaying though I am not getting any error. I am retrieving data from database mysql. here is my code
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container2',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'diseas Per area'
},
// tooltip: {
// formatter: function() {
// return '<b>' + this.point.name + '</b>: ' + this.y+ 'd Count';
// }
// },
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>' + this.point.name + '</b>: ' + this.y;
}
},
showInLegend: true
}
},
series: []
};
$.getJSON("fcount.php", function(json) {
options.series = json;
chart = new Highcharts.Chart(options);
});
});
<div id="container2" style="height: 550px; min-width: 310px; max-width:800px; margin: 0 auto"></div>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
kindly tell me what I am doing wrong. It does not show any error but still it does not display
my php code is
<?php
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysql_query("SELECT `Area` AS Zone, COUNT( `Diease` ) AS problem FROM table GROUP BY `Area` ");
//$rows = array();
$rows['type'] = 'pie';
$rows['name'] = 'Diease Count';
//$rows['innerSize'] = '50%';
while ($r = mysql_fetch_array($result)) {
$rows['data'][] = array('zone '.$r['area'].'"', $r['problem']);
}
$rslt = array();
array_push($rslt,$rows);
print json_encode($rslt, JSON_NUMERIC_CHECK);
mysql_close($con);
instead of push array into an empty array like this
$rslt = array();
array_push($rslt,$rows);
print json_encode($rslt, JSON_NUMERIC_CHECK);
use it like below
echo json_encode($rows);
The lack of data is probably caused by the format of your options.series. When using a pie chart, your series should be formatted like this:
options.series = [{ name: 'Browsers',
data: [ ["Firefox",60] , ["Chrome",40]]
}]
In this JSFiddle I used your options code to generate the chart. So if your options.series looks like shown above, the chart should work.

how to create proper json data format from mysql for highcharts

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"}]

Jquery flot pie with PHP MYSQL

I have some problems. Excuse me for my english.
I'ld display the datas but nothing !!
I dont know where is the probleme. I dont find it.
Thnaks you for your help.
code html
<div id="pie2" style="height:300px"></div>
code javascript
jQuery(document).ready(function ($){
var options = {
series: {
pie: {
show: true,
radius: 1,
label: {
show: true,
radius: 2 / 3,
tilt:0.5,
formatter: function(label, series)
{
return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">' + label + '<br/>' + Math.round(series.percent) + '% (' + series.data[0][1] + ')</div>';
},
background:
{
opacity: 0.8
}
}
}
},
legend: {
show: true
}
};
var dataset1 = <?php echo json_encode($pie);?>;
var data = [
{
"label": "Random Values",
"data": dataset1
}
];
var plotarea = $("#pie2");
$.plot( plotarea , data);
});
code PHP (source_pie.php)
$sql = "SELECT COUNT(rne) AS rne, dept FROM anuetab GROUP BY dept";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($sql)){
$pie[] = array(
'label'=>$row['dept'],
'data'=>$row['rne']
);
echo '<pre>';
print_r($pie);
echo '</pre>';
}
echo json_encode($pie);
try with mysql_fetch_row instead of mysql_fetch_assoc

Highcharts: Force show xAxis with datetime

My highcharts chart is showing like this now:
http://img90.imageshack.us/img90/3892/chart1p.png
But I need it to look like this:
http://img545.imageshack.us/img545/1333/chart2p.png
Currently its not showing empty values by hours.
My code:
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function () {
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'spline'
},
title: {
text: 'Earnings Today',
},
subtitle: {
text: ''
},
xAxis: {
type: 'datetime',
tickInterval: 3600 * 1000,
tickWidth: 0,
labels: {
align: 'center',
formatter: function () {
return Highcharts.dateFormat('%l%p', this.value);
}
},
},
yAxis: {
title: {
text: 'Earnings'
},
min: 0,
tickInterval: 2,
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 1
}
}
},
tooltip: {
valueDecimals: 2,
crosshairs: true,
formatter: function () {
return '$' + this.y;
}
},
series: [{
name: 'Earnings Today, USD'
}
]
}
jQuery.get('data_today.php', null, function (tsv) {
var lines = [];
earnings = [];
try {
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function (i, line) {
line = line.split(/\t/);
date = Date.parse(line[0] + ' UTC');
val = line[1];
earnings.push([date, parseFloat(line[1].replace(',', '.'), 10)]);
});
} catch (e) {}
options.series[0].data = earnings;
chart = new Highcharts.Chart(options);
});
});
</script>
data_today.php
<?php
session_start();
require_once('config.php');
require_once('config_mysql.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if (!$db)
{
die("Unable to select database");
}
$result = mysql_query("SELECT earn_date,SUM(amount) as val FROM user_earnings WHERE user_id='$USER_ID' AND DATE(earn_date) = DATE(NOW()) GROUP BY earn_date");
if ($result)
{
while ($row = mysql_fetch_array($result))
{
$d = date("l, F, j, Y G:i:s", strtotime($row["earn_date"]));
echo $d . "\t" . $row['val'] . "\n";
}
}
else
{
die(mysql_error());
}
mysql_close($link);
?>
So, (if its not enough clear yet) I need this code to show whole day and show also empty values by hour.
I have almost zero experience of highcharts and javascript, so I need some help with this :)
Also looking for alternative way for running MySql query inside index.php so I dont need data_today.php
Thanks
Set the xAxis as below
xAxis: {
ordinal: false
}
For empty spaces you should have null values. Then set connectNulls: false.
Example

Issues Rendering Highcharts - Populating through PHP/MySQL

I'm hoping someone can help me here, I've been looking at highcharts as a way of graphing my dynamic data from my sql db....What I've come up with so far is below, it's strange, it seems correct, the data is correct, however, I can't get my chart to render, now I've tried viewing the chart through both Chrome and IE but with no results, can anyone see where I might've gone wrong, or where there is an error...my data is passing into the JS arrays, so there's an issue with the rendering end... Any help would be much appreciated. I have closed off my html tag, but for some reason it isn't displaying in this post...if anyone has any suggestions I would be happy to hear them!
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src='highcharts.js' type='text/javascript'> </script>
<script src='exporting.js' type='text/javascript'> </script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"type="text/javascript"></script>
</head>
<body>
<?php
include "connect_db.php";
$SQL1 = "SELECT review.reviewForum AS reviewForum,
COUNT(CASE WHEN mom.result = 'Approved' THEN 'yes' ELSE NULL END) AS Approved,
COUNT(CASE WHEN mom.result = 'NOT Approved' THEN 'yes' ELSE NULL END) AS Not_Approved,
COUNT(CASE WHEN mom.result = 'Cancelled' THEN 'yes' ELSE NULL END) AS Cancelled
FROM review INNER JOIN mom ON mom.reviewId = review.reviewId GROUP BY review.reviewForum";
$result1 = mysql_query($SQL1);
$data1 = array();
while ($row = mysql_fetch_array($result1)) {
$data1[] = $row['reviewForum'];
}
$result2 = mysql_query($SQL1);
$data2 = array();
while ($row = mysql_fetch_array($result2)) {
$data2[] = $row['Approved'];
}
$result3 = mysql_query($SQL1);
$data3 = array();
while ($row = mysql_fetch_array($result3)) {
$data3[] = $row['Not_Approved'];
}
$result4= mysql_query($SQL1);
$data4 = array();
while ($row = mysql_fetch_array($result4)) {
$data4[] = $row['Cancelled'];
}
?>
<script type="text/javascript">
$(document).ready(function() {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'TC REVIEW RESULT STATS'
},
xAxis: {
categories: [<?php echo join($data1, ',') ?>],
},
yAxis: {
min:0
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 50,
y: 35,
floating: true,
shadow: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [ {
name: 'Approved',
data: [<?php echo join($data2, ',') ?>],
pointStart: 0
//pointInterval
},
{
name: 'Unapproved',
data: [<?php echo join($data3, ',') ?>],
pointStart: 0
//pointInterval
},
{
name: 'Cancelled',
data: [<?php echo join($data4, ',') ?>],
pointStart: 0
//pointInterval
},
]
});
});
</script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
I suggest you start trying to render one without generated code. If that doesnt work, you might want to share that on jsfiddle and we can have a look :-). If it does work, you should compare it with the generated code.
{
name: 'Cancelled',
data: [<?php echo join($data4, ',') ?>],
pointStart: 0
//pointInterval
}, // This comma is a syntax error
]
Do you see that comma? You don't put commas before '}', because you have that in multiple places.
Take out the comma after the categories statement under xAxis.
 xAxis:  {
categories: [<?php echo join($data1, ',') ?>],
},
Should be
xAxis:  {
categories: [<?php echo join($data1, ',') ?>]
},
I think thre real reason is here:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"type="text/javascript"></script>
<script src='highcharts.js' type='text/javascript'> </script>
<script src='exporting.js' type='text/javascript'> </script>
First load jQuery, then Highcharts.

Categories