Highcharts Display values from sql via json - php

Hello I try to use Highcharts with data's from an sql Database by using json.
There are all doing but I can't see any values
I get the Data's with this script:
<?php
header('content-type: text/html; charset=utf-8');
include("db.inc.php");
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWOR
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(DB_NAME, $con);
$sth0 = mysql_query("SELECT `DATETIME` FROM `dg_wall24` WHERE DATETIME >
NOW()INTERVAL 1 HOUR");
$rows0 = array();
$rows0['name'] = 'DATETIME';
while($r0 = mysql_fetch_array($sth0)) {
$rows0['data'][] = $r0['DATETIME'];
}
$sth1 = mysql_query("SELECT `dg_t01` FROM `dg_wall24` WHERE DATETIME >
NOW()INTERVAL 1 HOUR");
$rows1 = array();
$rows1['name'] = 'dg_t01';
while($r1 = mysql_fetch_array($sth1)) {
$rows1['data'][] = $r1['dg_t01'];
}
$sth2 = mysql_query("SELECT `dg_h01` FROM `dg_wall24` WHERE DATETIME >
NOW() INTERVAL 1 HOUR");
$rows2 = array();
$rows2['name'] = 'dg_h01';
while($r2 = mysql_fetch_array($sth2)) {
$rows2['data'][] = $r2['dg_h01'];
}
$result = array();
array_push($result,$rows0);
array_push($result,$rows1);
array_push($result,$rows2);
print json_encode($result);
mysql_close($con);
?>
The Result:
[{"name":"DATETIME","data":["2013-04-27 08:17:52","2013-04-27 08:22:52","2013-04-27 08:27:53","2013-04-27 08:32:54","2013-04-27 08:37:55","2013-04-27 08:42:55","2013-04-27 08:47:56","2013-04-27 08:52:57","2013-04-27 08:57:58","2013-04-27 09:02:58","2013-04-27 09:07:59","2013-04-27 09:13:00"]},{"name":"dg_t01","data":["22.40","22.40","22.40","22.40","22.30","22.30","22.40","22.40","22.40","22.40","22.40","22.40"]},{"name":"dg_h01","data":["40.20","40.40","40.50","40.80","40.70","40.70","40.80","40.90","41.00","41.00","40.90","40.70"]}]
In the Highchart I can See the timeline on the x Axis and the name of the values but no line and no values.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 40
},
title: {
text: 'Dachgeschoss',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
//categories: []
},
yAxis: {
title: {
text: 'Temperatur & Luftfeuchtigkeit'
},
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("data2.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/modules/exporting.js"></script>
<script type="text/javascript" src="js/themes/gray.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
It is possible that I have an problem with the Dataformat (float, int...) or with the Point in the values?
Many thanks for the help

The problem is indeed that your JSON object contains String values instead of Float values for your data:
{ ... "data":["40.20","40.40","40.50", ... ]}
I don't know what the field type in your database is, and I'm no PHP coder, but you could try setting the JSON_NUMERIC_CHECK option on json_encode.
If that doesn't work for you, you could also convert the Strings using parseFloat in Javascript:
for (var i = 0, num; num = json[1].data[i]; i++)
{
json[1].data[i] = parseFloat(num);
}
See my example on Fiddle.

Related

creating real time graph using mysql data and highchart

I have a records.values table in myDB.When new data is inserted into this table I want to change the graph.I used php and highchart but there is nothing can be seen from browser.What is wrong thing in my code.I use ubuntu 14.04.
index.php
<!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">
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("/home/cea/Desktop/deneme/data.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'REgion vs. type',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
title: {
text: 'Amount'
},
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: json
});
});
});
});
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
data.php
accessing database values
<?php
$con = mysql_connect("localhost:3306","root","963369");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
else print "connected!";
mysql_select_db("records", $con);
$sth = mysql_query("SELECT region FROM records.values");
$rows = array();
$rows['name'] = 'Region';
while($r = mysql_fetch_array($sth)) {
$rows['data'][] = $r['region'];
}
$sth = mysql_query("SELECT type FROM records.values");
$rows1 = array();
$rows1['name'] = 'Type';
while($rr = mysql_fetch_assoc($sth)) {
$rows1['data'][] = $rr['type'];
}
$sth = mysql_query("SELECT value FROM records.values");
$rows2 = array();
$rows2['name'] = 'Value';
while($rrr = mysql_fetch_assoc($sth)) {
$rows2['data'][] = $rrr['value'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
array_push($result,$rows2);
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
What is the missing point in here? **I just started to learn php and highcharts. Thank you..

Graph not being plot using High Charts and PHP

I am getting temperature from MySQL DB and Now I want to plot graph for the same over last 3 days. But the graph doesnt get plotted .
Here is the code for two files.
//Sql.php
<?php
// if you want to send request from a html file stored
// locally uncomment the line below
header('Access-Control-Allow-Origin: *');
// in the commands "mysql_..." change the following:
// xxxx - your SQL server address (np: www.abc.com)
// yyyy - user name
// zzzz - password
// qqqq - database name
// watch out for the capital letters!
mysql_connect("192.168.100.107:3306", "root", "hannan786") or die(mysql_error());
mysql_select_db("pi") or die(mysql_error());
// describe the date ragne - here: the last 3 days
$phpdate=time()- (3*24 * 60 * 60);
$datefrom = date( 'Y-m-d H:i:s', $phpdate );
$dateto = date( 'Y-m-d H:i:s', time() );
$data = mysql_query("SELECT * FROM temp WHERE `time` > '$datefrom'
AND `time` < '$dateto' ORDER BY time ASC") or die(mysql_error());
$rowcount = mysql_num_rows($data);
$counter=1;
// prepare the answer needed by Highcharts:
echo '{
"title": {"text": "temperature"},
"chart": {"renderTo": "container"},
"series": [{"name": "temperature", "data":[';
// fill the data from the database,
// here - the data of interest is stored in column "Temp4":
while($r = mysql_fetch_assoc($data)) {
echo '['.strtotime($r["time"])*1000 . ', '.$r["temperature"]/10 .']';
if($counter < $rowcount){
echo ", ";
}
$counter=$counter+1;
}
// finalize the answer
echo' ]}]}';
mysql_free_result($data);
?>
And this is the another page , Which is index.html , where I want to plot the graph .
<!DOCTYPE HTML>
<html>
<head>
<html xmlns="http://www.w3c.org/1999/xhtml"; xml:lang="pl" lang="pl">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Hannan</title>
<!-- pliki js znajdziesz na www.jquery.com i www.highcharts.com-->
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript" src="js/highcharts.js"></script>
<script type="text/javascript" src="js/themes/grid.js"></script>
<script src="https://code.highcharts.com"></script>
<script type="text/javascript">
var options;
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
options = {
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%e of %b',
hour: '%H:%M<br>%d %b'
}
},
yAxis: [{
title: {
text: null
},
labels: {
align: 'left',
x: 3,
y: 16,
formatter: function() {
return Highcharts.numberFormat(this.value, 0);
}
},
showFirstLabel: false
}, {
linkedTo: 0,
gridLineWidth: 0,
opposite: true,
title: {
text: null
},
labels: {
align: 'right',
x: -3,
y: 16,
formatter: function() {
return Highcharts.numberFormat(this.value, 0);
}
},
showFirstLabel: false
}],
legend: {
align: 'left',
verticalAlign: 'top',
y: 0,
floating: true,
borderWidth: 0
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%a, %d.%b %H:%M', this.x)+'<br><b>'+ this.series.name +' '+ this.y +'°C</b>';
}
},
plotOptions: {
series: {
cursor: 'pointer',
marker: {
enabled: false,
lineWidth: 1
}
}
}
};
$.getJSON("sql.php", function(json) {
var options1 = $.extend(json, options);
chart = new Highcharts.Chart(options1);
});
});
</script>
</head>
<body>
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
The charts are using HighChart Library. Please help me out if you have any idea , Why the graph or chart isint working properly.
Thank You .

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.

Could my servers configuration stop json from working?

I am trying to work through a tutorial regarding getting a JSON string from MySQL and preparing it for highcharts, but it's not working and I have no idea why....
HTML:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function () {
$.getJSON("data.php", function (json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Revenue vs. Overhead',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
title: {
text: 'Amount'
},
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: json
});
});
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
The JSON string is produced using the file
data.php:
<?php
$con = mysql_connect("*****", "*****", "*****");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*****", $con);
$sth = mysql_query("SELECT revenue FROM projections_sample");
$rows = array();
$rows['name'] = 'Revenue';
while ($r = mysql_fetch_array($sth)) {
$rows['data'][] = $r['revenue'];
}
$sth = mysql_query("SELECT overhead FROM projections_sample");
$rows1 = array();
$rows1['name'] = 'Overhead';
while ($rr = mysql_fetch_assoc($sth)) {
$rows1['data'][] = $rr['overhead'];
}
$result = array();
array_push($result, $rows);
array_push($result, $rows1);
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
If I enter a JSON string manually into data.php the charts is displayed as expected.
[{
"name": "Revenue",
"data": [23987, 24784, 25899, 25569, 25897, 25668, 24114, 23899, 24987, 25111, 25899, 23221]
}, {
"name": "Overhead",
"data": [21990, 22365, 21987, 22369, 22558, 22987, 23521, 23003, 22756, 23112, 22987, 22897]
}]
I'm assuming my connection details are correct, because if I purposely enter the wrong password I get the MySQL connection error...
“Could not connect: Access denied for user ‘*****’#'localhost’ (using password: YES)”
Also, I get “True” returned when I add “echo #mysql_ping() ? ‘true’ : ‘false’;” to the bottom of the page.
Because I'm convinced it should be working I'm wondering if there is anything related to server configuration that could be preventing me from using JSON?
if you can't use JSON_NUMERIC_CHECK (because it requires PHP 5.3.3 (json.constants))
you can cast to int [$number = (int)"1234";]
in
while ($r = mysql_fetch_array($sth)) {
$rows['data'][] = (int)$r['revenue']; // <- (int)
}
and
while ($rr = mysql_fetch_assoc($sth)) {
$rows1['data'][] = (int)$rr['overhead']; // <- (int)
}
than
print json_encode($result);

Highchart LineChart MySQL data

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src='http://code.highcharts.com/highcharts.js' type='text/javascript'> </script>
<script src='http://code.highcharts.com/modules/exporting.js' type='text/javascript'> </script>
</head>
<body>
<?php
$con = mysql_connect('localhost', 'root', '123456') or die('Error connecting to server');
mysql_select_db("aplikace", $con);
$SQL1 = "SELECT * FROM data";
$result1 = mysql_query($SQL1);
$data1 = array();
while ($row = mysql_fetch_array($result1)) {
$data1[] = $row['cas'];
}
$result2 = mysql_query($SQL1);
$data2 = array();
while ($row = mysql_fetch_array($result2)) {
$data2[] = hexdec($row['pars_data']);
}
?>
<script type="text/javascript">
$(document).ready(function() {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line'
},
title: {
text: 'Comming Data'
},
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: 'Data',
data: ['<?php echo join($data2, "','") ?>'],
// pointStart: 0
//pointInterval
},
]
});
});
</script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
Hi guys, I dont kwno where I have a mistake, could you help me please? On X-axis should be the datetime from column CAS-> it works but it doesnt display column PARS_DATA. Thanks for your help, thanks.
MySQL TABLE screen:
Chart which I see:
You should convert your date time field to unix timestamp for process on it.
so strtotime function is good idea.
In your code, follow this :
$result=mysql_query($sql)or die(mysql_error());
if(mysql_num_rows($result)>0){
while($row=mysql_fetch_array($result))
{
$uts=strtotime($row['time']); //convert to Unix Timestamp
$date=date("l, F j, Y H:i:s",$uts); //standard template for draw chart
echo $date . "\t" . $row['new_cost']. "\n"; //only this template work
}
$sql: your sql query text.
$result: feedback.
$row['new_cost']: my field for cost.
for more details, follow this link
good luck

Categories