I'm trying to implement an import/export per month graph for my website using Google Charts API with a MySQL database. Everything is ok, but I'm looking for a way to show in my chart also the months without imports or exports. Could someone please help me? Here is a screenshot of my graph, as you can see some months missing
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var dati = google.visualization.arrayToDataTable([
['Month', 'Imports', 'Exports'],
<?php
$q = "SELECT month(date) AS month, SUM(imports) AS imports, SUM(exports) AS exports FROM table WHERE year(date)=2020 GROUP BY month(date)";
$res_q=mysqli_query($db,$q);
//fetch data
while ($row = mysqli_fetch_array($res_q)) {
$entry = "['".$row{'month'}."',".$row{'imports'}.",".$row{'exports'}."],";
echo $entry;
}
?>
]);
var options = {
chart: {
title: 'Imports and Exports',
subtitle: 'Bar chart',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(dati, google.charts.Bar.convertOptions(options));
}
Consider the following:
<?php
$array = array(1,2,3,5,7,11);
for($i=1;$i<=12;$i++){
if(in_array($i,$array)){echo $i.' yes<br>';} else {echo $i.' no<br>';}
}
?>
You can use an additional array that holds your data and that contains all the months:
<?php
// prepare array with default 'empty' data
$entries = []
for ($m = 1; $m <= 12; $m++) {
$entries[$m] = '[]';
}
And then add the existing data to this array by overwriting the default values:
// fetch data
while ($row = mysqli_fetch_array($res_q)) {
$entries[$row['month']] = "['".$row{'month'}."',".$row{'imports'}.",".$row{'exports'}."]";
}
// output
echo implode(',', $entries);
Related
I am using google charts (on a php webpage) with data from an sql DB. The problem i am having is that it is not display the field names and values properly it simply displays the value of the first field "expense". It should be showing two fields "expense" and "income" with the values in the db. Any ideas what i am doing wrong ?
my code below:
<?php
$dbhandle = new mysqli('localhost','root','','useraccounts');
echo $dbhandle->connect_error;
$query = "SELECT * FROM ctincome";
$res = $dbhandle->query($query);
?>
<html>
<head>
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['expense','income'],
<?php
while($row=$res->fetch_assoc())
{
echo "['".$row['expense']."','".$row['income']."'],";
}
?>
]);
var options = {
title: 'Expenses to Income',
pieHole: 0.4,
};
var chart = new
google.visualization.PieChart(document.getElementById
('donutchart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="donutchart" style="width: 900px; height: 500px;"></div>
</body>
</html>
the values for the income column should be numbers, not strings.
remove the single quotes from the second column.
from...
echo "['".$row['expense']."','".$row['income']."'],";
to...
echo "['".$row['expense']."',".$row['income']."],";
I have three suggestions based on my experience in crossbrowser or javascript bugs I solved.
First point : You are just echoing, you need to use concatenation.
<?php
$data = '';
while($row=$res->fetch_assoc())
{
$data .= "['".$row['expense']."','".$row['income']."'],";
}
?>
var data = google.visualization.arrayToDataTable([
['expense','income'],
<?php echo $data; ?>
]);
second point : In javascript last comma may or may not work, its best to not to append comma if it's a last row.
var data = google.visualization.arrayToDataTable([
['expense','income'],
<?php
while($row=$res->fetch_assoc())
{
if(last row )
$data .= "['".$row['expense']."','".$row['income']."']";
else $data .= "['".$row['expense']."','".$row['income']."'],";
}
?>
]);
third suggestion : check data type of var data before and after the concatenation
I am trying to create a bar chart using google charts and mysqli. But my code is not working when I try to insert php in the googlecharts it is no longer showing up on the webpage.
my code:
<!--GOOGLE CHARTS-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
//PHP
<?php
if(isset($_GET['id'])) {
$ID= 'id';
$childId=$_GET['id'];
$rowId=$_GET['id'];
$chartsql = "SELECT `feis_entered`, `competition_level1`, `dance_name1`, `firstpl_score1`, `2ndpl_score1`, `3rdpl_score1` FROM `mark_cards1` WHERE id = '$rowId'";
$chartres = mysqli_query($con,$chartsql);
$chartrow=mysqli_fetch_array($chartres);
if($chartres){
$compName = '.$chartrow["feis_entered"].';
$compLvl = '.$chartrow["competition_level1"].';
$danceName = '.$chartrow["dance_name1"].';
$first = '.$chartrow["firstpl_score1"].';
$second = '.$chartrow["2ndpl_score1"].';
$third = '.$chartrow["3rdpl_score1"].';
}
}
?>
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Ranking');
data.addColumn('number', 'Score');
data.addRows([
['1st Place', <?php echo $first;?>],
['2nd Place', <?php echo $second;?>],
['3rd Place', <?php echo $third;?>]
]);
var data = google.visualization.arrayToDataTable([
['Element', 'Score', { role: 'style' }],
[ '1st Place', <?php echo $first;?>, 'color: #91b224',],
[ '2nd Place', <?php echo $second;?>, 'color: #91b224',],
[ '3rd Place', <?php echo $third;?>, 'color: #91b224',],
]);
// Set chart options
var options = {title:'<?php echo $compName - $compLvl - $danceName;?>',
colors: ['#91b224'],
is3D:true,
width:600,
height:550};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
first place, second place, and third place are the fields. CompName, compLvl, and danceName are the title.
EDIT picture of source code below
the chart values should be numbers instead of strings...
try removing the quotes...
from...
$first = '.$chartrow["firstpl_score1"].';
$second = '.$chartrow["2ndpl_score1"].';
$third = '.$chartrow["3rdpl_score1"].';
to...
$first = $chartrow["firstpl_score1"];
$second = $chartrow["2ndpl_score1"];
$third = $chartrow["3rdpl_score1"];
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
I have the following Google Charts code and I'm trying to connect it with MySQL, I have tried each and everything with it available on the internet but it still shows just one entry of SQL result set, although I have 10 entries in it. On the internet I found the $row_num counter thing and since including it in my code, I have been able to query one entry but I want to query all entries with it. Please help me with this and let me know what mistake (if any) I have been making, Following is my PHP code:
[<?php
``$dbhandle= new mysqli('localhost','root','8317','record');
//echo $dbhandle->connect_error();
$query= "SELECT * from download_manager";
$res= $dbhandle->query($query);
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':\['bar'\]});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable(\[
\['Title', 'No. of Downloads'\],
<?php
$total_rows = mysqli_num_rows($res);
$row_num = 0;
if (mysqli_num_rows($res) > 0) {
while($row=$res->fetch_assoc())
{
$row_num++;
if ($row_num == $total_rows){
echo "\['".$row\['filename'\]."',".$row\['downloads'\]."\]";
}
}
}
else
{
echo "0 results";
}
?>
\]);
var options = {
width: 800,
chart: {
'title': 'Top 10 Downloads',
subtitle: 'for the last month'
},
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
}
};
var chart = new google.charts.Bar(document.getElementById('dual_x_div'));
chart.draw(data, options);
};
</script>
</head>
<body>
See Also : Downloads in the Last 7 Years <br> <br>
<div id="dual_x_div" style="width: 900px; height: 500px;"></div>
</body>
</html>][1]
You have missed adding a comma , in your PHP data loop. Try with the following:
echo "\['".$row\['filename'\]."',".$row\['downloads'\]."\],";
My code is:
['checkio','money'],
<?php while($row = mysql_fetch_array($que)){ ?>
['<?php echo $row['checkio']?>' , <?php echo $row['money']?>],
<?php } ?>
According to my sources I should use a loop.
The problem with using a loop is that it cannot specify a separate color..
Its result is:
['checkio','money']
['in',1000]
['out',200]
all the data are the same color.
So, What should I do?
Not sure which chart are you using, but if you are drawing the chart with javascript, you can set a series color in the options of the chart. Here is an example:
var options = {};
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
options.series={};
for(var i = 0;i < data.getNumberOfRows();i++){
options.series[i]={color:getRandomColor()}
}
Full example: http://jsfiddle.net/z2ewqoe1/