I'm going through a bit of a learning process, in order to create a small database backed reporting system for my company.
The intent is to draw a multi line chart using Google Charts, based on a mysql database.
I've managed to get the data to echo from the mysql database, but it's not generating the chart. All I get is the echo, and a blank space where the chart should be. The echo is shown for debugging purposes.
Here is the code :
<?php include 'confile.php';
$qry = "SELECT time,p1,p2,p3,p4 from $db WHERE date = '2016-03-02' ORDER BY time ASC";
$result = $conn->query($qry);
if($result === FALSE) {
echo mysql_errno($result) .": ". mysql_error($result) ."/n";
die(mysql_error());
}
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Time', 'type' => 'datetime'),
array('label' => 'Probe 1', 'type' => 'number'),
array('label' => 'Probe 2', 'type' => 'number'),
array('label' => 'Probe 3', 'type' => 'number'),
array('label' => 'Probe 4', 'type' => 'number')
);
while($r = mysqli_fetch_assoc($result)) {
$temp = array();
$temp[] = array($r['time']);
$temp[] = array($r['p1']);
$temp[] = array($r['p2']);
$temp[] = array($r['p3']);
$temp[] = array($r['p4']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?$jsonTable?>);
var options = {
title: 'Recorded Temperatures',
legend: {position: 'bottom' },
width: 800,
height: 600
};
var chart = new google.visualization.Table(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>
And this is the 'echo' output
{"cols":[{"label":"Time","type":"datetime"},{"label":"Probe 1","type":"number"},{"label":"Probe 2","type":"number"},{"label":"Probe 3","type":"number"},{"label":"Probe 4","type":"number"}],"rows":[{"c":[["03:02:07"],["270.26"],["298.40"],["111.54"],["228.06"]]},{"c":[["03:28:42"],["273.23"],["190.43"],["245.69"],["283.21"]]},{"c":[["07:26:04"],["144.33"],["217.26"],["206.53"],["167.68"]]},{"c":[["12:13:20"],["153.15"],["277.23"],["167.20"],["240.88"]]}]}
This is test data, using a test query on the db. Once I understand the formatting to render the chart, it will be setup to allow the user to select which date to view, etc.
This was the closest existing question I can find, but doesn't seem to answer the question.
Not able to generate a Google Chart using MySQL table data as the data source
Following the answer of #MickMackusa, I managed to hack this together to get it to work, by ensuring the mysql/php array was output in a manner acceptable to Google Charts.
Thanks to #MickMacUSA for his assistance.
The final, working code, is below.
<?php include 'confile.php';
$qry = "SELECT time,p1,p2,p3,p4 from $db WHERE date = '2016-04-16' ORDER BY time ASC";
$result = $conn->query($qry);
if($result === FALSE) {
echo mysqli_errno($result) .": ". mysqli_error($result) ."/n";
die(mysqli_error());
}
$i = 0; //iteration counter - start at 0
$totalRows = mysqli_num_rows($result); // we need this to know when to change the output
$targetRows = $totalRows - 1; //row indies start from 0, not 1.
foreach ($result as $row){
$comTime = str_replace(":",",",$row['time']); // for each row, remove the : and put , in its place
if ($targetRows == $i) { // if the index is the same value as the target (ie, it's the last row)...
$temp = "[[".$comTime."],".($row['p1']).",".($row['p2']).",".($row['p3']).",".($row['p4'])."]". PHP_EOL;
} else {
$temp = "[[".$comTime."],".($row['p1']).",".($row['p2']).",".($row['p3']).",".($row['p4'])."],". PHP_EOL;
}
$i = $i + 1;
$rows[] = $temp;
}
$table = $rows;
$data = implode($table); //format the table as a single string, with line returns
//echo $i;
//echo $data;
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
data.addColumn('timeofday','Time');
data.addColumn('number','Probe 1');
data.addColumn('number','Probe 2');
data.addColumn('number','Probe 3');
data.addColumn('number','Probe 4');
data.addRows([
<?php echo $data; ?> //dump the result into here, as it's correctly formatted
]);
var options = {
title: 'Recorded Temperatures',
legend: { position: 'bottom' },
width: 900,
height: 500,
hAxis: { format: 'hh:mm:ss' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(data, options);
}
</script>
</body>
</html>
Your number values must be formatted differently and you want timeofday not datetime.
According to: https://developers.google.com/chart/interactive/docs/reference#dataparam
Format your data to look like this:
{cols:
[
{"label":"Time","type":"timeofday"},
{"label":"Probe 1","type":"number"},
{"label":"Probe 2","type":"number"},
{"label":"Probe 3","type":"number"},
{"label":"Probe 4","type":"number"}
],
rows:
[
{c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
{c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
{c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
{c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
]
}
And you must echo it in the javascript:
change:
<?$jsonTable?>
to:
<?php echo $jsonTable; ?>
And put your javascript code block just before your </body> tag.
This is the full working code using the above data format that I tested on my server:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable(
{cols:[
{"label":"Time","type":"timeofday"},
{"label":"Probe 1","type":"number"},
{"label":"Probe 2","type":"number"},
{"label":"Probe 3","type":"number"},
{"label":"Probe 4","type":"number"}
],
rows:[
{c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
{c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
{c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
{c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
]
});
var options = {
title: 'Recorded Temperatures',
legend: { position: 'bottom' },
width: 900,
height: 500,
hAxis: { format: 'hh:mm:ss' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</body>
</html>
This is an alternative format that will be simpler/clearer/easier to build/comprehend using your mysqli results:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
data.addColumn('timeofday','Time');
data.addColumn('number','Probe 1');
data.addColumn('number','Probe 2');
data.addColumn('number','Probe 3');
data.addColumn('number','Probe 4');
data.addRows([
[[03,02,07],270.26,298.40,111.54,228.06],
[[03,28,42],273.23,190.43,245.69,283.21],
[[07,26,04],144.33,217.26,206.53,167.68],
[[12,13,20],153.15,277.23,167.20,240.88]
]);
var options = {
title: 'Recorded Temperatures',
legend: { position: 'bottom' },
width: 900,
height: 500,
hAxis: { format: 'hh:mm:ss' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</body>
</html>
See the SO Demo provided by WhiteHat:
google.charts.load('current', {
callback: drawChart,
packages: ['corechart', 'table']
});
function drawChart() {
var data = new google.visualization.DataTable({cols: [
{"label":"Time","type":"timeofday"},
{"label":"Probe 1","type":"number"},
{"label":"Probe 2","type":"number"},
{"label":"Probe 3","type":"number"},
{"label":"Probe 4","type":"number"}
],
rows: [
{c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
{c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
{c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
{c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
]
});
var table = new google.visualization.Table(document.getElementById('chart_0'));
table.draw(data);
var options = {
title: 'Recorded Temperatures',
legend: {position: 'bottom' },
width: 800,
height: 600,
hAxis: {
format: 'hh:mm:ss'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_1'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_0"></div>
<div id="chart_1"></div>
I am pulling data from a mysql database in a PHP script and using google charts to display the data graphically. It worked fine when using a pie or bar chart with only 2 variables to deal with. Now I want to use a ComboChart. I have 4 fields in a table: Name, Date, Quanity, Cost. I want to have a ComboChart where along the x-axis is the Date, a bar graph will represent the Quantity, and a line graph will represent the Cost.
Here is the code I have so far. How can I go about doing this? In the drawChart() function there's no explicit order to what is on the x or y axis so how do I know which of my data is being displayed where? Does that depend on what order you select the data in during the mysqli_query?
// host, username, password and dbname are already declared
$conn = mysqli_connect($host, $username, $password);
if ($conn->connect_error) {
die("Could not connect: " . mysql_error()) . "<br>";
}
mysqli_select_db($conn, $dbname);
$qresult = mysqli_query($conn, "SELECT * FROM Scrap");
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Date', 'type' => 'string'),
array('label' => 'Quantity', 'type' => 'number'),
array('label' => 'Cost', 'type' => 'number')
);
$rows = array();
while ($r = $qresult->fetch_assoc()) {
$temp = array();
$temp[] = array('v' => (string) $r['Date']);
// Values of each slice
$temp[] = array('v' => (int) $r['Quantity']);
$temp[] = array('v' => (float) $r['Cost']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'YTD Controllable Scrap Costs',
seriesType:'bars',
series:{2: {type: 'line'}}
// width: 800,
// height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
So I tested around and I found out that the first column is the x-axis and the 2nd, 3rd, 4th, etc go on the y-axis. The reason the bar AND line graph weren't showing up was because in my drawChart() function, where it says: series:{2: {type: 'line'}}, the number 2 refers to the 3rd field for the y-axis since it is zero-indexed. I didn't have a 3rd field for the y-axis, so I switched it to series:{1: {type: 'line'}} and now I get a bar graph and a line graph.
Thanks for all the inputs from Stackoverflow. I am able to place the 2 google chart in one page, but the 2nd chart is showing below 1st chart. But i need both charts in parallel to each other.
Like:
1st chart from Left it should be 100th position, top =200 and 2nd chart should be 300th position, top=200. How can i achieve that. I used chartArea:{left:20,top:0,width:"50%",height:"75%"}, but i am not getting
<?php
$con=mysql_connect("","root","") or die("Failed to connect with database!!!!");
mysql_select_db("Loan_Bids", $con);
$sth = mysql_query("SELECT A.Bid_Size, B.Rating from bids_data A, loan_data B Where A.LoanID = B.LoanID");
$rows = array();
$rows1 = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
array('label' => 'Bid_Size', 'type' => 'number'),
array('label' => 'Rating', 'type' => 'number')
);
$table1 = array();
$table1['cols'] = array(
array('label' => 'Bid_Size', 'type' => 'number'),
array('label' => 'Rating', 'type' => 'number')
);
$rows = array();
$rows1 = array();
while($r = mysql_fetch_assoc($sth)) {
$Ratingval = $r['Rating'];
if ($Ratingval == 1 )
{
$temp = array();
// the following line will be used to slice the Pie chart
$temp[] = array('v' => (int) $r['Bid_Size']);
// Values of each slice
$temp[] = array('v' => (int) $r['Rating']);
$rows[] = array('c' => $temp);
}
if ($Ratingval == 2 )
{
$temp1 = array();
// the following line will be used to slice the Pie chart
$temp1[] = array('v' => (int) $r['Bid_Size']);
// Values of each slice
$temp1[] = array('v' => (int) $r['Rating']);
$rows1[] = array('c' => $temp1);
}
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
$table1['rows'] = $rows1;
$jsonTable1 = json_encode($table1);
echo $jsonTable1;
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?php echo $jsonTable?>);
var options = {
title: 'Rating1',
is3D: 'true',
color:'red',
hAxis: {title: 'Interest Rate'},
vAxis: {title: 'Bid Size'},
width:200,height:200
};
var data1 = new google.visualization.DataTable(<?php echo $jsonTable1?>);
var options1 = {
title: 'Rating2',
is3D: 'true',
hAxis: {title: 'Interest Rate'},
vAxis: {title: 'Bid Size'},
width:200,height:200
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
var chart1 = new google.visualization.ScatterChart(document.getElementById('chart_div1'));
chart1.draw(data1, options1);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
<div id="chart_div1"></div>
</body>
</html>
You need to use CSS to position the container divs on the page, not the chartArea options. Something like this should work:
#chart_div, #chart_div1 {
float: left;
width: 50%;
}