Related
I am looking forward chart like this https://i.stack.imgur.com/a6dAq.png with this code
php + html:
$sql = "SELECT val1 , val2 ,t
FROM DvojeHodnoty
INNER JOIN Pristroje ON DvojeHodnoty.dev_name = Pristroje.dev_name
WHERE t>'$startdate2' AND t< '$enddate2' AND Pristroje.nazev_pristroje='$pristroj' order by val1 asc;";
$result = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_array($result))
{
$t = $t.'"'.date('d.m.y H:i:s', $row['t']/1000).'",';
$hodnota = $hodnota.'"'.$row['val1'].'",';
$hodnota2 = $hodnota2.'"'.$row['val2'].'",';
}
$start = date('d.m.y', $startdate2/1000);
$end = date('d.m.y', $enddate2/1000);
$t = trim($t,",");
$hodnota = trim($hodnota,",");
$hodnota2 = trim($hodnota2,",");
}
<div id="chart-container" style="background: white">
<canvas id="chart"></canvas>
<script>
var ctx =document.getElementById("chart").getContext('2d');
var myChart = new Chart(ctx, {
type:'line',
data: {
labels: [<?PHP echo $hodnota2; ?>],
datasets:
[
{
label: '<?PHP echo $start;?> - <?PHP echo $end; ?> Přístroj: <?PHP echo $pristroj;?> ',
data: [<?PHP echo $hodnota; ?>],
backgroundColor:'transparent',
borderColor:'rgba(255,99,132)',
borderWidth: 3
}]
},
options: {
scales: {
yAxes:[{
scaleLabel: {
display: true,
labelString: 'σ',
fontSize: 20
}
}],
xAxes:[{
scaleLabel: {
display: true,
labelString: 'ε',
fontSize:20
}
}]
}
}
})
</script>
</div>
but so far I got only this https://i.stack.imgur.com/Ri8Ho.png.
I don't know how to create chart with two variables, I tried scatter but so far I am stuck with no ability to create graph with x,y line as values. Is there any easy way to create chart with two variables? If so can you help me/ give me some documentation? (I've seen one scatter chart with fix values, but I am not able to do it with php echo (with values from database) since I need to have variable values since user will choose values depends on chosen date. So far I got only 1 value (y) and two values but with text (numbers counted as text not as value) so chart looks weirdly (0,1,-1 still on same line not like normal graph showned up).
The problem was that data type was VARCHAR and for sorting it I need INT. Problem solved
I'd like to know if is possible to do that with Flot chart, because I'm not sure...
I have a table on a database with 3 rows: Date Start, Date End, Medication
Mi PHP code:
$sql = "SELECT * FROM medications ORDER BY DateStart";
$stmt = $PDO -> query($sql);
$result=$stmt -> fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row){
$dateini= $row['DateStart'];
$datend= $row['DateEnd'];
$medic= $row['Medication'];
$data1 = array(strtotime($dateini)*1000,$medic);
$data2 = array(strtotime($datend)*1000,$medic);
$data3[] = array($data1,$data2);
}
If I do:
echo json_encode($data3);
I get the array:
[[[1456531200000,"12"],[1456704000000,"12"]],[[1456531200000,"16"],[1456704000000,"16"]],[[1456617600000,"13"],[1456790400000,"13"]],[[1456704000000,"14"],[1457049600000,"14"]]]
<script>
var data3 = <?php echo json_encode($data3)?>;
$(function() {
var datasets = [
{
label: "Medication",
data: data3,
yaxis: 1,
color: "Yellow",
points: { symbol: "diamond", fillColor: "Yellow",show: true, radius: 6}
}
];
$.plot($("#flot-placeholder"), datasets ,options);
</script>
This: $.plot($("#flot-placeholder"), datasets ,options) don't plot anything, but if I do:
$.plot($("#flot-placeholder"), data3,options);
I get
It would be possible to get the graphic writing datasets (in $.plot) instead data3?
Two issues with your datasets array:
Your data3 array has multiple data series but you try to put it all into one data set object in the datasets array. Put each data series in a separate object (with its own options where neccessary).
var datasets = [{
label: "Medication",
data: data3[0],
yaxis: 1,
color: "Yellow",
points: {
symbol: diamond,
fillColor: "Yellow",
show: true,
radius: 6
}
}, {
label: "Medication",
data: data3[1],
yaxis: 1,
color: "red",
points: {
symbol: diamond,
fillColor: "red",
show: true,
radius: 6
}
}, ... ]
Flot has no build-in diamond symbol, you have to provide a function which draws a diamond.
function diamond(ctx, x, y, radius, shadow) {
var size = radius * Math.sqrt(Math.PI) / 2;
ctx.moveTo(x - size, y);
ctx.lineTo(x, y + size);
ctx.lineTo(x + size, y);
ctx.lineTo(x, y - size);
ctx.lineTo(x - size, y);
}
See this fiddle for a full working example.
Hi I am trying to get data from MySql table and show the data in Highcharts by using PHP and Json
I have try the example from internet and it is working fine but when I try to get data from my file it show nothing.
What I am trying to do:
I am creating table of office attendance system and trying to show record day by day. So at y axis I want to count names of employees and x axis the date of attendance.
Problem: Nothing Is show from mu json.
Here is what my Json looks like:
[["Hamza","07\/04\/2014"],
["Junaid","07\/04\/2014"],
["Usman","07\/04\/2014"],
["Rajab","07\/04\/2014"],
["Hamza","08\/04\/2014"],
["Junaid","08\/04\/2014"],
["Usman","08\/04\/2014"],
["Rajab","08\/04\/2014"]]
I am having to value names and dates.
My PHP which is creating my Json code:
// Set the JSON header
header("Content-type: text/json");
$result = mysqli_query($con,"SELECT * FROM attendence");
$a=array();
while($row = mysqli_fetch_array($result)) {
$row['name'] . "\t" . $row['date']. "\n";
$b=array();
array_push($b,$row['name']);
array_push($b,$row['date']);
array_push($a,$b);
}
echo json_encode($a);
and this is my Jquery code:
$(function() {
$.getJSON('highchart.php', function(data) {
// Create the chart
$('#chart').highcharts('StockChart', {
rangeSelector : {
selected : 1,
inputEnabled: $('#chart').width() > 480
},
title : {
text : 'Attendence'
},
series : [{
name : 'Empolyees',
data : data,
tooltip: {
valueDecimals: 2
}
}]
});
});
});
In the json_encode() you need to use JSON_NUMERIC_CHECK flag to avoid use string in your JSON
In the highstock you need to have timestamps and value, not name and date.
Dates should be timestamp, and as first element in array, not second as you have.
If you want to get a count of all people on a given day, you need to write a SQL query that returns that information. Assuming that date field is a datetime type and name is of varchar type:
SELECT COUNT(name) FROM attendence GROUP BY DATE(date);
perhaps you need to define what kind of data your x-axis will have
take a look at this fiddle (taken from highcharts website)
$(function () {
$('#container').highcharts({
xAxis: {
type: 'datetime'
},
series: [{
data: [
[Date.UTC(2010, 0, 1), 29.9],
[Date.UTC(2010, 2, 1), 71.5],
[Date.UTC(2010, 3, 1), 106.4]
]
}]
});
});
I cannot get Highcharts to graph a scatter plot of 2 series. Actually, the graph isn't even showing up. Please help me determine what I'm doing wrong. I cannot find a scatter plot example to go off of and I am very new to this. I've got json data from a php file that looks like:
[[65,44],[66,37],[67,42],[68,55],[65,50],[65,41],[65,41],[68,41],[69,42],[70,47],[69,55],[67,45],[67,49],[67,53],[67,49],[68,51],[68,55],[68,57],[70,53],[69,66],[68,54],[69,52],[68,48]][[75,36],[72,42],[75,44],[69,56],[72,40],[73,37],[77,34],[77,40],[74,50],[77,45],[77,43],[75,47],[73,52],[73,50],[75,44],[72,54],[71,57],[72,57],[74,55],[74,54],[75,47],[78,45],[75,43]]
This should be two series in an (x,y) format. I want to graph these on a scatter plot in HighCharts. My HighCharts code is:
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("comfortgb1b.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container4',
type: 'scatter',
marginRight: 175,
marginBottom: 50
},
title: {
text: 'Comfort Level',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
title: {
enabled: true,
text: 'Temp (F)'
},
min: 60,
max: 85,
startOnTick: true,
endOnTick: true,
showLastLabel: true
},
yAxis: {
title: {
text: 'Humidity (%RH)'
},
min: 30,
max: 100
},
plotOptions: {
scatter: {
marker: {
radius: 5,
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: false
}
}
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: '{point.x} F, {point.y} %RH'
}
},
series: [{
name: 'Night',
data: json(1)
}, {
name: 'Night',
data: json(2)
});
});
});
});
</script>
Thanks in advance!
The php file that is creating the json data is below. How would I separate these arrays with a comma?
$result1 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) NOT BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret1 = array();
while($item = mysql_fetch_array($result1)) {
$avg_return1 = $item['avg_return'];
$avg_hum1 = $item['avg_hum'];
$ret1[] = array($avg_return1,$avg_hum1);
}
$result2 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret2 = array();
while($item = mysql_fetch_array($result2)) {
$avg_return2 = $item['avg_return'];
$avg_hum2 = $item['avg_hum'];
$ret2[] = array($avg_return2,$avg_hum2);
}
echo json_encode($ret1, JSON_NUMERIC_CHECK);
echo json_encode($ret2, JSON_NUMERIC_CHECK);
Not sure about this, but at first glance I think the array returned from the php file requires an additional square bracket outside it in order to be parsed as proper json. Currently it is:
[[65,44],[66,37]..][[75,36],[72,42]..]
From what I know, this is just two arrays. What you want is to enclose these arrays within an array. Try changing this to:
[[[65,44],[66,37]..],[[75,36],[72,42]..]]
That is, add an extra square bracket outside and separate the two arrays using a comma.
In addition, here:
series: [{
name: 'Night',
data: json(1)
}, {
name: 'Night',
data: json(2)
});
json(1) and json(2) are interpreted as function calls. You should instead use:
series: [{
name: 'Night',
data: json[0]
}, {
name: 'Night',
data: json[1]
});
EDIT ---- Edited as per OP edits
Also as requested, in order to add the commas and proper formatting, the php file can be changed at the last two lines as follows:
echo "[".json_encode($ret1, JSON_NUMERIC_CHECK).",";
echo json_encode($ret2, JSON_NUMERIC_CHECK)."]";
You have several things giving you problems. See this fiddle: http://jsfiddle.net/nbwN9/1/
First, I don't think your json is in the proper format for a 2 series plot. You have two arrays of data just butted up to each other rather than in another array. The linked fiddle corrects that (and stuffs it into a var since the getJSON() call will fail within jsFiddle). Each point is an array of (x,y) coords. Each series.data is an array of points. Your json will need to be an array of series.data arrays. So we're looking at nested arrays 3 deep.
Second, you seem to have a malformed set of chart options. Most notable is that your series node (with name and data) is inside your plotOptions node when it should be outside of it. And that series node is not terminated properly.
Third, once you get your json data and your chart options formatted correctly, accessing the json array is done like so:
series: [{
name: 'Night',
data: json[0]
}, {
name: 'Day',
data: json[1]
}]
The array is 0-based (so the first record will be indexed with a 0, second record with a 1, etc) and is access using the brackets [] not parentheses ()
Sorry, I renamed one of your series to "Day" so I could see the difference in the chart.
As far as the PHP script... try this:
$result1 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) NOT BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret1 = array();
while($item = mysql_fetch_array($result1)) {
$avg_return1 = $item['avg_return'];
$avg_hum1 = $item['avg_hum'];
$ret1[] = array($avg_return1,$avg_hum1);
}
$result2 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret2 = array();
while($item = mysql_fetch_array($result2)) {
$avg_return2 = $item['avg_return'];
$avg_hum2 = $item['avg_hum'];
$ret2[] = array($avg_return2,$avg_hum2);
}
echo json_encode(array($ret1,$ret2), JSON_NUMERIC_CHECK);
I'm trying to make graphs in PHP and MySQL using jQuery, specifically with Highcharts library, I have managed to make the chart with data from MySQL database, but these data show some data if they are in the databases but not others, for example, a query that yields 10 results 5 are good, but the other five did not, I have done some research on the web and I understand it is due to a problem when I pass the result of my query in MySQL by json_encode, I hope some of you can tell me because I have this error or if I'm misusing the JSON, thank you very much.
Code:
index.php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Incidencias</title>
<script type="text/javascript" src="../js/jquery-1.7.1.min.js" ></script>
<script type="text/javascript" src="../js/highcharts.js" ></script>
<script type="text/javascript" src="../js/themes/grid.js"></script>
<script type="text/javascript" src="../js/export.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'pieClientes',
defaultSeriesType: 'pie',
marginRight: 10,
marginBottom: 25
},
title: {
text: 'top 10. Clientes con m\u00e1s incidencias',
x: -10
},
subtitle: {
text: '',
x: -20
},
tooltip: {
formatter: function() {
return '<b>'+ this.point.name +'</b>: <b>'+ this.y +' incidencias</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
type: 'pie',
name: 'Browser share',
data: []
}]
}
$.getJSON("datosCliente.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<div style="font-size: 12p; font-family: Calibri, Candara, Segoe, Segoe UI, Optima, Arial, sans-serif; align="left" >
<h1>Dashboard incidencias SCI</h1>
<div>
<div id="pieClientes" style="width: 770px; height: 450x; margin: 0"></div>
</body>
</html>
datosCliente.php
<?php
include"../clases/conexion.php";
$result = mysql_query("SELECT
clientes.cliente,
COUNT(incidencias.idIncidencia) AS nIncidencias
FROM incidencias
INNER JOIN clientes ON incidencias.idCliente = clientes.idCliente
GROUP BY incidencias.idCliente
ORDER BY nIncidencias DESC
LIMIT 0,10");
$rows = array();
while($r = mysql_fetch_array($result))
{
$row[0] = $r[0];
$row[1] = $r[1];
array_push($rows,$row);
}
//print json_encode($rows, JSON_PRETTY_PRINT);
echo json_encode($rows, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
mysql_close($con);
?>
The error is for example when I want to show 10 row of the database in the graph, it show me the results of this form:
1st. row-> show me "slice"
2nd. row-> the registerok,
3th. row-> show me "slice"
4. row-> the registerok,
5. row-> the registerok,
6.row-> show me "slice"
7.row->the registerok,
8.row-> show me "slice"
9.row->the registerok,
10.row-> show me "slice"
The problem is that in the graph (pie) displays correct data but not others, it is as if some records or tubiese skipped a limit of 5 registrros, not I do not know where I'm wrong. :(
thanks for helping :)
First of all I would try to give the array elements a value, instead of using the index. Give your array key a name. As well remove all the uppercase letters from your encode. I am on an ipad and unable to code, but let me know if you have questions.