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 .
Related
Highchart scroll problem
When I scroll using the in built scroll bar of highcharts, some of the data is not being shown in the highcharts table, but when I scroll again, the data is shown and some other data is omitted out.
The code that I have used is given below for reference
code:-
<?php
$colorArray = ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'];
$string ='[';
for($i=1;$i<=15;$i++){
$yearString = rand(2016,2018);
$monthString = rand(1,12);
$dateString = rand(1,28);
$endYearString = rand(2019,2021);
$string .= "{ start: Date.UTC($yearString, $monthString, $dateString),end: Date.UTC($endYearString, $monthString, $dateString),name: 'Initiative ".$i."',color: '".$colorArray[rand(0,8)]."', label:'Initiative ".$i."' },";
}
$string .= "{ start: Date.UTC(2020, 1, 1),end: Date.UTC(2021, 1, 12),name: 'Qus',color: '".$colorArray[rand(0,8)]."', label:'Qus' },";
$string .= "{ start: Date.UTC(2021, 1, 12),end: Date.UTC(2021, 1, 22),name: 'Qus',color: '".$colorArray[rand(0,8)]."', label:'Qus' },";
$string .= "{ start: Date.UTC(2021, 1, 23),end: Date.UTC(2021, 5, 31),name: 'Qus',color: '".$colorArray[rand(0,8)]."', label:'Qus' },";
for($i=1;$i<=30;$i++){
$yearString = rand(2016,2018);
$rnd = rand(1,5);
for($j=1;$j<$rnd;$j++){
$monthString = rand(1,12);
$dateString = rand(1,28);
$endMonthString = rand(1,12);
$endDateString = rand(1,28);
$endYearString = rand(2016,2021);
$string .= "{ start: Date.UTC($yearString, $monthString, $dateString),end: Date.UTC($endYearString, $endMonthString, $endDateString),name: 'Qus ".$i." - ".$j."',color: '".$colorArray[rand(0,8)]."', label:'Qus ".$i." - ".$j."' },";
}
}
$string .= "]";
// echo $string;die;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://code.highcharts.com/gantt/highcharts-gantt.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<style>
#container {
max-width: 1200px;
margin: 1em auto;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
Highcharts.setOptions({
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
Highcharts.ganttChart('container', {
chart: {
spacingLeft: 1,
style: {
fontFamily: ' Roboto, sans-serif;',
// fontWeigth: 'bolder'
}
},
title: {
text: 'Gantt Chart with Navigation'
},
yAxis: {
uniqueNames: true,
min: 0,
max: 7,
scrollbar:{
enabled : true
}
},
xAxis: {
currentDateIndicator: true,
type: 'category',
title: {
text: null
},
min: 0,
// max: 8,
scrollbar: {
enabled: true
},
tickLength: 0
},
tooltip: {
xDateFormat: '%a %b %d, %H:%M'
},
plotOptions:{
series: {
pointWidth: 13,
dataLabels: {
enabled: true,
format: '{point.label}',
style: {
cursor: 'default',
pointerEvents: 'none'
}
},
}
},
navigator: {
enabled: true,
series: {
type: 'gantt',
pointPlacement: 0.5,
pointPadding: 0.25
},
yAxis: {
min: 0,
max: 3,
reversed: true,
categories: []
}
},
scrollbar: {
enabled: true
},
rangeSelector: {
enabled: true,
selected: 5
},
series: [{
name: 'Project 1',
events:{
click: function(event){
console.log(event)
console.log(this)
alert("Clicked");
}
},
dataLabels: {
enabled: true,
style: {
textOutline: 0
}
},
data: <?php echo $string; ?>
}]
});
const callback = function(){
let text = document.querySelectorAll('.highcharts-data-label-color-undefined')
let box = document.querySelectorAll('.highcharts-partfill-original')
text.forEach((el,index)=>{
let child = el.children[0];
let boxWidth = box[index].getBoundingClientRect().width;
let textWidth = child.getBoundingClientRect().width;
// console.log(textWidth,boxWidth)
if (textWidth > boxWidth){
child.style.opacity = "0";
}else{
// child.textContent = z;
child.style.fill = "white";
child.style.opacity = "1";
}
})
};
callback();
window.addEventListener('resize', callback);
</script>
</body>
</html>
scrollbar:{
enabled : true
},
events: {
setExtremes: function(e){
let main = document.querySelector('.highcharts-plot-background').getBoundingClientRect();
const call = function(){
let bound = main.y + main.height;
let lines = document.querySelectorAll('.highcharts-tick')
let texts = document.querySelectorAll('.highcharts-treegrid-node-level-1');
texts.forEach(el=>{
let textlines = el.getBoundingClientRect();
if(textlines.y > main.y && textlines.y < bound-20){
el.style.visibility = "visible"
}else{
el.style.visibility = "hidden"
}
})
lines.forEach(el=>{
let pathlines = el.getBoundingClientRect();
let parent = el.parentNode
if(parent.classList.contains('highcharts-yaxis')){
if(pathlines.y > main.y && pathlines.y <bound){
el.style.visibility = "visible"
el.visibility = "visible"
}else{
el.style.visibility = "hidden"
el.visibility = "hidden"
}
}
})
}
setTimeout(function(){ call();},500)
}
}
},
I am making one area graph dynamically in that I want to set the Data array dynamically. I have created variable and assign it Scores which example I have given below
$dataPoints = '30, 10, 40, 20, 30, 10, 50, 30, 30, 30, 40';
var dataPoints1 = '<?php echo $dataPoints; ?>';
var areaChart = c3.generate({
bindto: '#area-chart',
data: {
columns: [
['Score', dataPoints1]
],
types: {
data1: 'area',
Score: 'area-spline'
}
},
tooltip: {
show: true
},
legend: {
show: false
},
axis: {
x: {
show: false
},
y: {
show: false
},
},
grid:{
focus:{
show:false
}
}
});
But this Script is not working and it does not show a graph and if I set this value statically so it is working fine.
So can anybody help me with this...
Instead of fetching php string into js variable, pass php string directly to column, it will work
var areaChart = c3.generate({
bindto: '#area-chart',
data: {
columns: [
['Score', <?php echo $dataPoints; ?>] // use php variable directly
],
types: {
data1: 'area',
Score: 'area-spline'
}
},
tooltip: {
show: true
},
legend: {
show: false
},
axis: {
x: {
show: false
},
y: {
show: false
},
},
grid:{
focus:{
show:false
}
}
});
There is no need of dataPoints1 js variable.
EDIT
In that case,
In php I suppose ajax,
$dataPoints["Score"] = [30, 10, 40, 20, 30, 10, 50, 30, 30, 30, 40];
echo json_encode($dataPoints); die;
In JS
var chart = c3.generate({
bindto: '#area-chart',
data: {
url: 'your url to fetch above data',
mimeType: 'json',
types: {
data1: 'area',
Score: 'area-spline'
}
},
tooltip: {
show: true
},
legend: {
show: false
},
axis: {
x: {
show: false
},
y: {
show: false
},
},
grid: {
focus: {
show: false
}
}
});
This should solve your problem
I use your code as example and try to modify code with my database connection and sample table data.
Please try this, hope this will useful to you.
File (PHP + HTML + jQuery)
<?php
$servername = "localhost"; // Change with your server name
$username = "root"; // Change with your user name
$password = ""; // // Change with your password
$dbname = "test"; // // Change with your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT data FROM users"; // // Change with your table name
$result = $conn->query($sql);
$dataPoints = '';
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$dataPoints .= $row['data'];
$dataPoints .= ',';
}
rtrim($dataPoints);
echo $dataPoints;
} else {
echo "0 results";
}
$conn->close();
?>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>C3.js</title>
<style type="text/css">
body{
text-align: center;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.16/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
</head>
<body>
<div class="container">
<h1>Graphs made easy</h1>
<div id="chart"></div>
</div>
<script type="text/javascript">
var dataPoints1 = ["Score", <?php echo $dataPoints;?>];
console.log('dataPoints : ', <?php echo $dataPoints;?>);
console.log('data2 : ', dataPoints1);
var areaChart = c3.generate({
bindto: '#chart',
data: {
columns: [
dataPoints1
],
types: {
data1: 'area',
Score: 'area-spline'
}
},
tooltip: {
show: true
},
legend: {
show: false
},
axis: {
x: {
show: false
},
y: {
show: false
},
},
grid:{
focus:{
show:false
}
}
});
</script>
</body>
</html>
Output
I am new to web programming, I have personal project to track expenditure.
Straight to the point, I have database data contains this month and last month total expenditure. I am able to show it manually (by echo). But i can't pass the value to highcharts series. Due to many small separate data, i want to populate it manually using php/mysql rather than json.
Graph2.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "mypassword";
$mysql_database = "mytraining";
$bd = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password, $mysql_database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query2 = "select year(date) as y, month(date) as m, sum(amount) as p from expenditure_bak group by year(date), month(date) order by m ASC";
$sth = mysqli_query($bd, $query2);
$rows = array();
$rows['name'] = 'Revenue';
while($r = mysqli_fetch_array($sth)) {
$rows['data'][]= round($r['p'],2);
}
//echo join($rows['data'], ','); //able to display correct value 660.2,60
?>
PopupGraph.html
<?php
include('graph2.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Monthly Expenditure</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$('#container').highcharts({
title: {
text: 'Monthly Expenditure'
},
xAxis: {
categories: ['Jun', 'Jul']
},
yAxis: [{
min: 0,
title: {
text: ''
}
}, {
min: 0,
opposite: false, //optional, you can have it on the same side.
title: {
text: 'Average'
}
}
],
labels: {
items: [{
html: 'Monthly Expenditure',
style: {
left: '50px',
top: '18px',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'black'
}
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.x + '</b><br/>' +
this.series.name + ': ' + this.y
/*+ '<br/>' + 'Total: ' + this.point.stackTotal*/;
}
},
series: [{
type: 'spline',
name: 'Average',
yAxis: 1, //to make y axis
//data: [660.2,60], //able to show correct graph with static input
data: [<?php echo join($rows[data], ',') ?>],
marker: {
lineWidth: 2,
lineColor: Highcharts.getOptions().colors[3],
fillColor: 'white'
}
}]
});
});
</script>
</head>
<body>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
</html>
So, what is the correct code to be put inside data: [] in the highcharts series.
Output should be like JSFiddle but using dynamic data from database obviously.
Finally, I want to display something like
Expenditure Tracking
You will likely need to encode your data. I recommend that you take a look at the answer from here Pass a PHP array to a JavaScript function. Based on this, you should be able to do something like this:
JSON.parse(<?php echo json_encode(join($rows[data], ',')) ?>);
then you should be able to get the result that you want. You might not need the JSON.parse.
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.
<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