Using jquery highchart with dynamic php values fetched from mysql datatable - php

I tried finding a well explained example or at least a definition, but had no luck.
So basically I have a data-table, I want to fetch some values from it and display it using jquery high-chart.
So far, I have this:
<?php
include("connect.php"); //script for connecting to database and defining the $connection
$query = "SELECT * FROM meetings";
$result = mysql_query($query, $connection);
$numberOfMeetings = 25; //this is mocked here so you can better understand the code
echo '<table>
<tbody>';
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td>' . $row['memberName'] . '</td>';
echo '<td>' . ($row['timesPresent'] / $numberOfMeetings) * 100 . '%</td>';
echo '</tr>';
}
?>
I get a nice simple table with a lot of rows and 2 columns. First column is showing the name of the member and the second one is showing the percentage how many times he has been present on a meeting.
My question is now that I have this data-table and those values (I can always put the values in arrays if needed) how can I display it like this done on the fiddle: http://jsfiddle.net/uDrQq/3/
I somehow need to pass the categories and the data from php values to the jquery code,but how?

To use this you have to pass DB values from PHP to Javascript
use php on same page or get the values from AJAX
here is the demo how to use on same page
<?php
include("connect.php"); //script for connecting to database and defining the $connection
$query = "SELECT * FROM meetings";
$result = mysql_query($query, $connection);
$numberOfMeetings = 25; //this is mocked here so you can better understand the code
$membername=array();
$timepresent=array();
while ($row = mysql_fetch_array($result)) {
$membername[]=$row['memberName'];
$timepresent[]=($row['timesPresent'] / $numberOfMeetings) * 100;
}
$membername="'".implode("','", $membername)."'";
$timepresent=implode(",", $timepresent);
?>
//pass values in Javascript
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Percentage of members on meetings'
},
xAxis: {
categories: [<?php echo $membername?>],
title: {
text: "Members"
}
},
yAxis: {
min: 0,
title: {
text: 'Percentage',
align: 'middle'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueDecimals: 2,
valueSuffix: ' %'
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
credits: {
enabled: false
},
series: [{
name: 'Present: ',
data: [<?php echo $timepresent?>]
}]
});
});

Related

How can use SQL query to get values from DB in arrays for a line chart

I'm trying to fetch data from DB for a line graph using the below code.
<?php
$dataPoints = array(
$sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while($row1 = $result1->fetch_assoc()) {
array("y" => 25, "label" => "Sunday"), ?>
} } else { }
);
?>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: ""
},
axisY: {
title: ""
},
data: [{
type: "line",
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
Using the above code it gives as error as Un-expected Syntax error, expecting ) instead of ; at $dataPoints line
However if i m to remove the sql query, graph plots with static data perfectly.
Any Help is greatly appreciated..
I have to commend you for keeping PHP code and JavaScript separate. This is a very good idea. However, if you want to fetch all records from MySQL using PHP and mysqli library you do not need to have any loop. You can just fetch everything into an array and then display with json_encode() in JavaScript.
<?php
// import your mysqli connection before
$result1 = $conn->query("SELECT * FROM chart_data_column WHERE value = 'now'");
$dataPoints = $result1->fetch_all(MYSQLI_ASSOC);
?>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: ""
},
axisY: {
title: ""
},
data: [{
type: "line",
dataPoints: <?= json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
<?= is short for <?php echo
You put the entire query inside the array. You need to separate them. Also, you have "chart_data_column" where the table name should be.
$dataPoints = array();
$sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while ($row = $result1->fetch_assoc()) {
$dataPoints[] = $row;
}
}

How to loop in PHP and display all rows

So I have this problem in looping in PHP, I can't seem to display, it only displays the first row. I want to display all 18 places and at the same time all places have different counts/data each. I think I'm missing a lot in PHP.
//This part of code displays the names and counts the met conditions
$sql = "SELECT b.name as brgy0,(SELECT COUNT(brgy_id) FROM tbl_fire_info where YEAR(date_of_report)=$year AND MONTH(date_of_report)=$smonth and status=1 AND brgy_id=b.barangayID) as cnt FROM tbl_barangay as b";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$numData = $row['cnt'];
$brgyData = $row['brgy0'];
//This part of code displays the data in the graph, I decided to loop it 18 times
new Chart(document.getElementById("bar-chart-grouped"), {
type: 'bar',
data: {
labels: ['<?php if(isset($_POST['submit'])){echo $haz;} ?>'],
datasets: [ //barangays
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
{
label: "<?php if(isset($_POST['submit'])){echo $brgyData;} ?>",
backgroundColor: "#3e95cd",
data: [<?php if(isset($_POST['submit'])){echo $numData;} ?>]
}
<?php
echo ",";
}
}else {
echo "0 results";
}
?>
]
},
options: {
title: {
display: true,
text: 'Number of reports'
}
}
});

Unable to display x-axis labels on multi-column mysql array in Highcharts

I have a mysql database containing multiple columns of power values captured over time, with time captured in the first column. I would like to plot the power values and display the time of day on the x-axis of a Highcharts chart. I am currently able to display the multiple Power values on the y-axis but I am unable to get the time of day to display on the chart. Here is the PHP code that partially works:
<?php
// Connect to database
$con = mysqli_connect("localhost","userid","passwd","power_readings");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Set the variable $rows to the columns Energy_Date and Total_watts
$query = mysqli_query($con,"SELECT Energy_Date,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Total_watts'];
}
// Set the variable $rows1 to the columns Energy_Date and Power_watts
$query = mysqli_query($con,"SELECT Energy_Date,Power_watts FROM combined_readings");
$rows1 = array();
$rows1['name'] = 'Neurio_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows1['data'][] = $tmp['Power_watts'];
}
// Set the variable $rows2 to the columns Energy_Date and Solar_watts
$query = mysqli_query($con,"SELECT Energy_Date,Solar_watts FROM combined_readings");
$rows2 = array();
$rows2['name'] = 'Solar_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows2['data'][] = $tmp['Solar_watts'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
array_push($result,$rows2);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
Can someone tell me how to change the code to pass the values from the time of day column properly?
Here is what the chart currently looks like:
When I made changes to the PHP to add the 'Energy_Date' field to the array passed to Highcharts (shown below) it results in a blank chart.
The array consists of fields that look like this (a time stamp followed by a power reading, separated by period:
"2018-02-21 16:56:00.052","2018-02-21 16:59:00.052","2018-02-21 17:02:00.039","2018-02-21 17:05:00.039","2018-02-21 17:08:00.039"
<?php
// Connect to database
$con = mysqli_connect("localhost","userid","passwd","power_readings");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Set the variable $rows to the columns Energy_Date and Total_watts
$query = mysqli_query($con,"SELECT Energy_Date,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_Date'].$tmp['Total_watts'];
}
// Set the variable $rows1 to the columns Energy_Date and Power_watts
$query = mysqli_query($con,"SELECT Energy_Date,Power_watts FROM combined_readings");
$rows1 = array();
$rows1['name'] = 'Neurio_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows1['data'][] = $tmp['Energy_Date'].$tmp['Power_watts'];
}
// Set the variable $rows2 to the columns Energy_Date and Solar_watts
$query = mysqli_query($con,"SELECT Energy_Date,Solar_watts FROM combined_readings");
$rows2 = array();
$rows2['name'] = 'Solar_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows2['data'][] = $tmp['Energy_Date'].$tmp['Solar_watts'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
array_push($result,$rows2);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
The html receiving this array looks like this:
<!DOCTYPE html>
<html lang="en">
<title>Combined Values Graph</title>
<head>
<meta http-equiv="refresh" content="180">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var x_values = [];
var chart;
$(document).ready(function() {
Highcharts.setOptions({
colors: ['#4083e9', '#99ccff', '#00ffff', '#e6e6e6', '#DDDF00', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
$.getJSON("values.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'mygraph',
type : 'spline',
borderWidth: 1,
zoomType: 'x',
panning: true,
panKey: 'shift',
plotShadow: false,
marginTop: 100,
height: 500,
plotBackgroundImage: 'gradient.jpg'
},
plotOptions: {
series: {
fillOpacity: 1
}
},
plotOptions: {
series: {
marker: {
enabled: false
}
}
},
title: {
text: 'Combined Power Readings'
},
subtitle: {
text: 'Total = Neurio + Solar Readings in Watts'
},
xAxis : {
title : {
text : 'Time of Day'
}
},
yAxis: {
title: {
text: 'Power (watts)'
},
plotLines: [{
value: 0,
width: 2,
color: '#ff0000',
zIndex:4,
dashStyle: 'ShortDot'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 120,
borderWidth: 1
},
plotOptions : {
spline : {
marker : {
radius : 0,
lineColor : '#666666',
lineWidth : 0
}
}
},
series: json
});
});
});
});
</script>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div class="container" style="margin-top:20px">
<div class="col-md-10">
<div class="panel panel-primary">
<div class="panel-body">
<div id ="mygraph"></div>
</div>
</div>
</div>
</div>
</body>
</html>
I have added the console statement to the bottom of the js like so:
series: json
});
console.log(json);
});
Here's what is shown in the browser console for PHP version 1 (The version that displays the graphs).
Browser console 1
Here's what is shown in the browser console for PHP version 2 (The version that gives a blank chart).
Browser console 2
Thanks for your helpful suggestions. I have changed the while loops to look like this:
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_UTC'];
$rows['data'][] = $tmp['Total_watts'];
}
The output of the PHP now looks like this:
[{"name":"Total_watts","data":[1519315164,93,1519315344,354]},{"name":"Neurio_watts","data":[1519315164,76,1519315344,309]},{"name":"Solar_watts","data":[1519315164,17,1519315344,45]}]
The data being passed to Highcharts (from the console) now looks like this:
Browser console 3
The chart is still wrong: the x-axis is not showing the timestamps and the chart is incorrect. Can anyone suggest how to change the PHP or html to correct this?
OK, I have updated the while loops to look like this:
$query = mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = [$tmp['Energy_UTC'],$tmp['Total_watts']];
}
The PHP output now looks like this:
[{"name":"Total_watts","data":[[1519387869,423],[1519388049,423],[1519388229,332],[1519388410,514],[1519388590,514]...
and the chart is now displaying UTC timestamps for each power value.
You are writing a large block of code with many duplicated components. I've taken the time to DRY your method. It is best practice to minimize calls to the database, so I've managed to combine your queries into one simple select.
Theoretically, you will only need to modify $colnames_labels to modify your HighChart. I have written inline comments to help you to understand what my snippet does. I have written some basic error checks to help you to debug if anything fails.
Code: (untested)
$colnames_labels=[
'Total_watts'=>'Total_watts',
'Power_watts'=>'Neurio_watts',
'Solar_watts'=>'Solar_watts'
];
$select_clause_ext=''; // declare as empty string to allow concatenation
foreach($colnames_labels as $colname=>$label){
$data[]=['name'=>$label]; // pre-populate final array with name values
// generates: [0=>['name'=>'Total_watts'],1=>['name'=>'Neurio_watts'],2=>['Solar_watts']]
$select_clause_ext.=",$colname";
// generates: ",Total_watts,Power_watts,Solar_watts"
}
$subarray_indexes=array_flip(array_keys($colnames_label)); // this will route resultset data to the correct subarray
// generates: ['Total_watts'=>0,'Power_watts'=>1,'Solar_watts'=>2]
if(!$result=mysqli_query($con,"SELECT UNIX_TIMESTAMP(Energy_Date) AS Stamp{$select_clause_ext} FROM combined_readings ORDER BY Energy_Date")){
$data=[['name'=>'Syntax Error (query error)','data'=>[0,0]]; // overwrite data with error message & maintain expected format
}elseif(!mysqli_num_rows($result)){
$data=[['name'=>'Logic Error (no rows)','data'=>[0,0]];
}else{
while($row=mysqli_fetch_assoc($result)){
foreach($subarray_indexes as $i=>$col){
$data[$i]['data'][]=[$row['Stamp'],$row[$col]]; // store [stamp,watts] data in appropriate subarrays
}
}
}
echo json_encode($data,JSON_NUMERIC_CHECK); // Convert to json (while encoding numeric strings as numbers) and print to screen

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

Having trouble passing data to Highcharts

I am trying to pull financial stock data of multiple companies from CSVs and display the data as separate series in a Highcharts/Highstocks line chart. I have the sources setup and I am able to pull data + convert to JSON, but I am having trouble passing the data off to Highcharts. I believe I am not using the most efficient method of preparing the data for Highcharts use, and I am hoping someone can give me direction on what I've done incorrectly. Please take a look at my code and make me aware of any inefficiencies or glaring errors you see.
PHP code:
date_default_timezone_set('America/Los_Angeles');
$stocks = array('MSFT' => 'http://ichart.finance.yahoo.com/table.csv?s=MSFT', 'AAPL' => 'http://ichart.finance.yahoo.com/table.csv?s=AAPL', 'FB' => 'http://ichart.finance.yahoo.com/table.csv?s=FB');
$stocks_data = array();
foreach ($stocks as $key=>$stock) {
$fh = fopen($stock, 'r');
$header = fgetcsv($fh);
$varname = $key . '_data';
$$varname = array();
while ($line = fgetcsv($fh)) {
${$varname}[count($$varname)] = array_combine($header, $line);
}
fclose($fh);
}
foreach($MSFT_data as $val){
$MSFT[] = strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close']; //sets the date as a javascript timestamp
}
$MSFT = json_encode($MSFT);
foreach($AAPL_data as $val){
$AAPL[] = strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close']; //sets the date as a javascript timestamp
}
$AAPL = json_encode($AAPL);
foreach($FB_data as $val){
$FB[] = strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close']; //sets the date as a javascript timestamp
}
$FB = json_encode($FB);
JS code:
$(function () {
var seriesOptions = [],
yAxisOptions = [],
colors = Highcharts.getOptions().colors;
seriesOptions[0] = {
name: 'MSFT',
data: <? php echo $MSFT; ?>
};
seriesOptions[1] = {
name: 'AAPL',
data: <? php echo $AAPL; ?>
};
seriesOptions[2] = {
name: 'FB',
data: <? php echo $FB; ?>
};
function createChart() {
chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? '+' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
});
}
});
If you have any questions or need further information, please let me know with a comment.
Thanks
BTW: I have all necessary assets included for Highcharts to work; when I replace my JS + PHP with example code from the Highcharts site, it works beautifully. So the problem clearly lies in my JS + PHP code.
Alright, I believe I found the problem, it lies in the way that you are storing each individual point in the array.
Instead of this (which is passing a string x,y separated by a comma):
strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close'];
You are going to want to use something like this (Highcharts accepts arrays or associative arrays):
array((strtotime($val['Date']) * 1000), ((float)$val['Close']));
That will store the X and Y variables as an array instead of comma separated string for the javascript to pass as data.

Categories