Highcharts and php for a dynamic chart - php

I have been at this some time trying to get highcharts to chart some data returned by php. I have done many searches and nothing works. I can write the php to deliver the data however it needs to be but how do you get it to dynamically chart it?????
I can deliver it as:
[["1372875867","44.8782806"],["1372875885","46.2020226"]]
or
[[1372876686,44.0655823],[1372876693,43.3360596], etc ]
but how do I get the data from the php output into the dyname example they display?????
!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
Highcharts.setOptions({
global : {
useUTC : false
}
});
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container',
events : {
load : function() {
// set up the updating of the chart eachsecond
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(),
y = Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title : {
text : 'Live random data'
},
exporting: {
enabled: false
},
series : [{
name : 'Random data',
data : (function() {
// generate an array of random data
var data = [], time = (new Date()).getTime(), i;
for( i = -999; i <= 0; i++) {
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
}
return data;
})()
}]
});
});
</script>
</head>
<body>
<script src="../../js/highstock.js"></script>
<script src="../../js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
my current php is:
<?php
// include("$_SERVER[DOCUMENT_ROOT]/config/config.php");
include("adodb5/adodb.inc.php");
$connection = new COM("ADODB.Connection") or die("Cannot start ADO");
$result_set = $connection->Execute("
SELECT tag, TIME, value
FROM picomp
WHERE TIME >= '*-3m' AND tag = 'xxx:xx_xxx.xxx'
");
$result_count = 0;
// $labels = array();
while (!$result_set->EOF) {
$pidate = date("U", strtotime($result_set->fields[1]) );
if ($result_count <> 0){
print ",";
}else{
print "[";
}
print "[".$pidate.",".$result_set->fields[2]."]";
// array_push("{$result_set->fields[2]}");
$result_count = $result_count +1;
$result_set->MoveNext();
// echo "testing";
}
print "];";

You can use HighchartsPHP which is a wrapper for Highcharts, which basically allows you to write all that JS code in PHP. It's very useful and pretty simple to use.
HighchartsPHP on GitHub

Your timestamp should be multiplied by 1000, and both values should be numbers.
Please familair with soultion, how to prepare JSON, because you only print "as JSON", but it is not.
Take look at http://php.net/manual/en/function.json-encode.php where some examples are introduced.

Related

JSON data not showing in highstock candlestick chart using PHP and SQL

I'm trying to display a highstock candlestick chart, but I can't achieve it.
My website shows a blank where the chart should be, but there's nothing showing in the chart.
How can I fix it to show the chart?
I have two scripts:
datachart.inc.php:
<?php
include '../dbh.php'; //It connects to the database
$sql = "SELECT * from table";
$result = $conn->query($sql);
$row = mysqli_fetch_array($result);
$data = array();
$count = 0;
while ($row=mysql_fetch_array($result))
{
$newdate = strtotime($row['date']) * 1000;
$data[] = array($newdate, (float)$row['open'], (float)$row['high'],
(float)$row['low'], (float)$row['close']);
$count++;
}
echo json_encode($data);
?>
index.htm:
<!DOCTYPE HTML>
<HTML>
<BODY>
<script>
$(function() {
$.getJSON('datachart.inc.php', function(data) {
// create the chart
chart = new Highcharts.StockChart({
chart : {
renderTo : 'container',
},
rangeSelector : {
selected : 1
},
title : {
text : 'Test Price'
},
series : [{
type : 'candlestick',
name : '',
data : data,
tooltip: {
valueDecimals: 2
},
dataGrouping : {
units : [
['week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]]
]
}
}]
});
});
});
</script>
<div id="container" style="height: 250px; min-width: 250px"></div>
</BODY>
</HTML>
Click here to see a picture of my sql table
Solved:
1) Import the javascript files
2) Remove "$row = mysqli_fetch_array($result);"
3) Change "while ($row=mysql_fetch_array($result))" to "while ($row=mysqli_fetch_array($result))"

Highcharts - parse json series

Im using this to draw column highcharts jsfiddle
i use this to gt JSON:
<?php
$query = mysql_query("SELECT
sales_raport_all.from_date,
sales_raport_all.to_date,
sales_raport_all.konto,
SUM(sales_raport_all.saldo_sprzedazy),
SUM(sales_raport_all.wartosc_kosztowa),
SUM(sales_raport_all.marza),
klienci_ax_all.sales_group,
klienci_ax_all.nazwa
FROM
sales_raport_all
INNER JOIN
klienci_ax_all
ON
sales_raport_all.konto=klienci_ax_all.konto_odbiorcy
WHERE
YEAR(from_date) = YEAR(CURDATE())
GROUP BY
sales_raport_all.from_date,
klienci_ax_all.sales_group
ORDER BY
sales_raport_all.from_date,
klienci_ax_all.sales_group");
$raw = array();
$dates = array();
while ($r = mysql_fetch_array($query)) {
$date = $r['from_date'];
if (!in_array($date, $dates)) $dates[] = $date;
$sales_group = $r['sales_group'];
$raw[$sales_group][$date] = intval($r['SUM(sales_raport_all.saldo_sprzedazy)']);
}
$data = array();
$data[0] = array('name' => "Date", 'data' => $dates);
foreach ($raw as $name => $d) {
$new_data = array('name' => $name, 'data' => array());
foreach ($dates as $date) {
$new_data['data'][] = isset($d[$date]) ? $d[$date] : 0;
}
$data[] = $new_data;
}
print json_encode($data);
in fiddle i use
chart3Options.series[0] = json[1];
...
is there a simple way to define all data in json? this data is variable and if i declare 11 variables and there will be only 7 then charts will not draw
JSON output for one date:
[{"name":"Date","data":["2014-01-01"]},{"name":"IN","data":[2580]},{"name":"KD","data":[5030]},{"name":"\u0141S","data":[12628]},{"name":"NN","data":[400]},{"name":"SG","data":[12979]},{"name":"TD","data":[15096]}]
// EDIT
i create new file:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'test',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'test'
},
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: []
}
$.getJSON("test2.php", function(json) {
options.xAxis.categories = json[0]['category'];
options.series[0] = {};
options.series[0].name = json[0]['name'];
options.series[0].data = json[0]['data'];
chart = new Highcharts.Chart(options);
});
});
</script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
and test2.php
<?php
$db_host = '******';
$db_user = '******';
$db_pass = '******';
$db_database = '******';
$link = mysql_connect($db_host,$db_user,$db_pass) or die('Nawiązanie połączenia z bazą danych nie było możliwe');
mysql_select_db($db_database,$link);
mysql_query("SET names UTF8");
$query = mysql_query("SELECT
sales_raport_all.from_date,
sales_raport_all.to_date,
sales_raport_all.konto,
SUM(sales_raport_all.saldo_sprzedazy),
SUM(sales_raport_all.wartosc_kosztowa),
SUM(sales_raport_all.marza),
klienci_ax_all.sales_group,
klienci_ax_all.nazwa
FROM
sales_raport_all
INNER JOIN
klienci_ax_all
ON
sales_raport_all.konto=klienci_ax_all.konto_odbiorcy
WHERE
YEAR(from_date) = YEAR(CURDATE())
GROUP BY
sales_raport_all.from_date,
klienci_ax_all.sales_group
ORDER BY
sales_raport_all.from_date,
klienci_ax_all.sales_group");
$result = array();
while($r = mysql_fetch_array($query)) {
$grupa = $r['sales_group'];
$datetime = $r['from_date'];
$result['name'][] = $datetime;
$result['category'][] = $grupa;
$result['data'][] = intval($r['SUM(sales_raport_all.saldo_sprzedazy)']);
}
$json = array();
array_push($json,$result);
print json_encode($json);
?>
JSON give me:
[{"name":["2014-01-01","2014-01-01","2014-01-01","2014-01-01","2014-01-01","2014-01-01"],"category":["IN","KD","\u0141S","NN","SG","TD"],"data":[2580,5030,12628,400,12979,15096]}]
Series looks greate but i dont know how to change category as in example http://jsfiddle.net/rubJS/
You can handle it in javascript. In other words, instead of defining variable for each <x,y> pair, return the data and let javascript construct the series.
For example, given your current output you can prepare X and Y values (in javascript) in separate arrays and write a function pushing these values into series. It can be done like this (using jQuery as an example):
function build_chart(x_values, y_values, options)
{
jQuery.each(x_values, function(item) {
options.xAxis.categories.push(x_values[item]);
});
var series = {
data: []
};
jQuery.each(y_values, function(item) {
series.data.push(parseInt(y_values[item]));
});
options.series.push(series);
chart = new Highcharts.Chart(options);
return chart;
}
Where variable options defines a chart template without series member (which is added by the above function)
EDIT
Following the edit in the question, here is the jsFiddle supporting it.
Note that the data in JSON is represented as array of arrays. First element in each array corresponds to the first category, second element in each array corresponds to the second category etc.
Apart from incorrect json format (which was mentioed) you need to push your dates as categorries in highcharts or use datetime type of axis, and then parse your date to timestamp.

Highstock json data not showing

Hey guys I am having trouble loading my data into the highstock charts.
My json.php calls on a sample MySQL database and looks something like this:
$result = mysql_query("SELECT UNIX_TIMESTAMP(date)*1000 AS timestamp,value from sample") or die('Could not query');
if(mysql_num_rows($result)){
echo 'Test';
$first = true;
$row=mysql_fetch_assoc($result);
while($row=mysql_fetch_row($result)){
if($first) {
$first = false;
} else {
echo ',';
}
$json_str = json_encode($row, JSON_NUMERIC_CHECK);
echo $json_str;
}
if(array_key_exists('callback', $_GET)){
$callback = $_GET['callback'];
echo $callback. '('.$json_str.');';
}
} else {
echo '[]';
}
mysql_close($db);
My index.htm which calls the Json.php is from the sample highstock template I just merely changed the getJson to match with my reference. Here is the code. Any help would be much appreciated, thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.getJSON('json.php', function(data) {
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : 'Test'
},
series : [{
name : 'Test',
data : data,
marker : {
enabled : true,
radius : 3
},
shadow : true,
tooltip : {
valueDecimals : 2
}
}]
});
});
});
</script>
</head>
<body>
<script src="js/highstock.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
Also, my json is parsed in this manner:
Test[1370899026000,10],[1370899026000,4],[1368177426000,11],[1370899026000,12],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,9],[1370899026000,14],[1370899026000,12],[1370899026000,10],[1370899026000,15],[1370899026000,12],[1378826226000,7],[1370899026000,9],[1370899026000,11],[1370899026000,7],[1370899026000,3],[1370899026000,6],[1370899026000,0],[1370899026000,11],[1370899026000,5],[1370899026000,9],[1370899026000,7],[1370899026000,8],[1370899026000,8],[1370899026000,9],[1370899026000,13],[1370899026000,11],[1370899026000,10],[1370899026000,13],[1370899026000,12],[1370899026000,12],[1370899026000,11],[1370899026000,13],[1370899026000,10],[1370899026000,8],[1370899026000,15],[1370899026000,13],[1370899026000,12],[1370899026000,14],[1370899026000,9],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,4],[1370899026000,4],[1370899026000,4],[1370899026000,13],[1370899026000,5],[1370899026000,10],[1370899026000,4],[1370899026000,10],[1370899026000,22],[1370899026000,9],[1370899026000,5],[1370899026000,9],[1370899026000,10],[1370899026000,5],[1370899026000,7],[1370899026000,10],[1370899026000,5],[1370899026000,7],[1370899026000,9],[1370899026000,9],[1370899026000,10],[1370899026000,6],[1370899026000,6],[1370899026000,6],[1370899026000,12],[1370899026000,7],[1370899026000,12],[1370899026000,8],[1370899026000,13],[1370899026000,12],[1370899026000,9],[1370899026000,7],[1370899026000,7],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,9],[1370899026000,10],[1370899026000,4],[1370899026000,11],[1370899026000,12],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,9],[1370899026000,14],[1370899026000,12],[1370899026000,10],[1370899026000,15],[1370899026000,12],[1370899026000,7],[1370899026000,9],[1370899026000,11],[1370899026000,7],[1370899026000,3],[1370899026000,6],[1370899026000,0],[1370899026000,11],[1370899026000,5],[1370899026000,9],[1370899026000,7],[1370899026000,8],[1370899026000,8],[1370899026000,9],[1370899026000,13],[1370899026000,11],[1370899026000,10],[1370899026000,13],[1370899026000,12],[1370899026000,12],[1370899026000,11],[1370899026000,13],[1370899026000,10],[1370899026000,8],[1370899026000,15],[1370899026000,13],[1370899026000,12],[1370899026000,14],[1370899026000,9],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,4],[1370899026000,4],[1370899026000,4],[1370899026000,13],[1370899026000,5],[1370899026000,10],[1370899026000,4],[1370899026000,10],[1370899026000,22],[1370899026000,9],[1370899026000,5],[1370899026000,9],[1370899026000,10],[1370899026000,5],[1370899026000,7]
Try closing with
[]
Highstock fiddle: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/stock/demo/areaspline/
Data of that fiddle: http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
Please take look at http://docs.highcharts.com/#preprocessing-data-from-a-database and take look at very simple example with json_encode:
tmp = array();
$tmp[] = array('A',5);
$tmp[] = array('B',6);
$tmp[] = array('C',1);
$tmp[] = array('D',2);
$rows = array();
for($i=0; $i<count($tmp); $i++)
{
$row['name'] = $tmp[$i][0];
$row['data'] = array($tmp[$i][1]);
array_push($rows,$row);
}
print json_encode($rows);
Highcharts:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
series: [{
name: 'Browser share',
data: []
}]
}
$.getJSON("datavotecolum.php", function(json) {
console.log(json);
options.series = json;
chart = new Highcharts.Chart(options,function(chart){
console.log(chart.series);
});
});
});

load data from text file into HIGHCHART graphic using PHP

I need to read data from text file that have many lines to load into highchart but if I put it as many lines, it will show the messy text please see this link. I don't want like this, I want that if have more than 20 lines in text file, it should be display 2 or 3 graphic of highchart to make the text is easy to see.I have the PHP code and script code as below:
<?php
$PMTA_DATE = date("Y-m-d");
$PMTA_FILE = file_get_contents("../stats_domain_emetteur.switchcall.com.".$PMTA_DATE.".txt");
$lineFromText = explode("\n", $PMTA_FILE);
//$number_bar_charts = 12;
$row = 0;
$cate = "";
$total ="";
$fail = "";
$mailSuc = "";
$title = "";
foreach($lineFromText as $line){
// if($row < $number_bar_charts){
$words = explode(";",$line);
$dateTime .= ','.$words[0];
if($title == ""){
$title = $words[0];
}
$cate .= ','."'$words[5]'";
$total .= ','.$words[6];
$fail .= ','.$words[7];
$mailSuc .= ','.((int)$words[6] - (int)$words[7]);
$row++;
// }
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Colunm Stack Percent Chat</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'PMTA4',
type: 'column'
},
title: {
text: 'PMTA4 - Unitead.info -<?php echo $title;?>'
},
xAxis: {
categories: [<?php echo substr($cate,1);?>]
},
yAxis: {
min: 0,
title: {
text: '% envoi'
}
},
tooltip: {
formatter: function() {
return ''+
this.series.name +': '+ this.y +' ('+ Math.round(this.percentage) +'%)';
}
},
plotOptions: {
column: {
stacking: 'percent'
}
},
series: [{
name: 'Total mail succesful',
data: [<?php echo substr($mailSuc,1);?>]
}, {
name: 'Total mail fail',
data: [<?php echo substr($fail,1);?>]
}]
});
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="PMTA4" style="min-width: 400px; height: 200px; margin-top:10px;"></div>
</body>
</html>
I do not know how to fix this, anyone help me please,Thanks.
If you take a look the reference you'll see that you can style labels.
Using staggerLines to display the label in more than one line, but it's not a good way and you can see why on my demo.
xAxys: {
labels: {
staggerLines: 10
}
}
demo
Or you can try to rotate them.
xAxys: {
labels: {
rotate: 90, // you can use 45 or 60 for a better readability
align: 'left'
}
}
demo
Reference:
http://api.highcharts.com/highstock#xAxis.labels.staggerLines

php/html with flot and mysql

I have issues with my javascript. Currently, I'm working on this javascript using flot to generate a graph, first by extracting data from mysql via php and then using json_encode to output the array data which will be used in the javascript. I'm not able to spot my mistake as to why my graph isn't plotting. Thanks!
<?php
include ('config2.php');
$tbl_name4 = EITMBS;
$data = array();
$sql="SELECT * FROM $tbl_name4";
$result=mysqli_query($link, $sql);
$row_cnt = mysqli_num_rows($result);
for ($nrow = 1; $nrow <= $row_cnt; $nrow=$nrow+1)
{
$sql="SELECT * FROM $tbl_name4 WHERE id = '$nrow'";
$result=mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
$data[$nrow] = $row[Power];
echo $data[1];
echo $data[2];
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Power Consumption</title>
<link href="layout.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../jquery.flot.js"></script>
</head>
<body>
<h1>Power Consumption</h1>
<div id="placeholder" style="width:600px;height:300px"></div>
<p id="hoverdata">Mouse hovers at
(<span id="x">0</span>, <span id="y">0</span>). <span id="clickdata"></span></p>
<p>A tooltip is easy to build with a bit of jQuery code and the
data returned from the plot.</p>
<p><input id="enableTooltip" type="checkbox">Enable tooltip</p>
<script type="text/javascript">
$(function () {
var graph = [];
var power = <?php echo json_encode($data);?>;
for (var i = 1; i < 9; i += 1) {
//alert(power[i]);
graph([i,[power(i)]);
}
var plot = $.plot($("#placeholder"),
[ { data: graph, label: "cos(x)" } ], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 }
});
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css( {
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 5,
border: '1px solid #fdd',
padding: '2px',
'background-color': '#fee',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
var previousPoint = null;
$("#placeholder").bind("plothover", function (event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if ($("#enableTooltip:checked").length > 0) {
if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
showTooltip(item.pageX, item.pageY,
item.series.label + " of " + x + " = " + y);
}
}
else {
$("#tooltip").remove();
previousPoint = null;
}
}
});
$("#placeholder").bind("plotclick", function (event, pos, item) {
if (item) {
$("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + ".");
plot.highlight(item.series, item.datapoint);
}
});
});
</script>
</body>
</html>
Your variable var power contains an object of integers for keys and floating point numbers in string format. You may have the wrong datatype enforced in your database (for mysql looks like you should be using FLOAT).
If you have PHP 5.3.3+ you can use the following to ensure numbers are stored in number format in a json encoded string:
json_encode($data, JSON_NUMERIC_CHECK);
If not you can cycle through the array before you json encode it:
for ($i in $data) {
$data[$i] = (float) $data[$i];
}
Secondly you are incorrectly converting the json encoded object to an array. Change:
graph([i,[power(i)]);
to:
graph.push([i, power[i]]);

Categories