I want to create a dynamic bar chart using Google's chart API and data obtained via MySQL. I'm using PHP to create the pages. I was able to create a simple chart with hard-coded values without any problem. Now I am trying to use some MySQL data instead, but with no luck. This code generate an empty screen.
<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(<?=$jsonTable1?>);
var options = {
title: '',
is3D: 'true',
width: 230,
height:145,
animation:{
duration: 100,
easing: 'out',
}
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div1'));
chart.draw(data, options);
}
</script>
<html>
<body>
<form method="post" action="">
<input type="text" name="regi" >
<br />
<input type="submit" name="submit" >
</form>
<div id="chart_div1"></div>
//php code
<?php
$DB_NAME = 'add';
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s
", mysqli_connect_error());
exit();
}
if(isset($_POST['submit']))
{
$regi=$_POST['regi'];
$sth = $mysqli->query('SELECT * FROM overall WHERE year="$regi"');
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'year', 'type' => "string"),
array('label' => 'Final CSE-1', 'type' => 'number')
);
foreach($sth as $r) {
$temp = array();
$temp[] = array('v' => (string) $r['subjectcode']);
// Values of each slice
$temp[] = array('v' => (int) $r['percentage']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable1 = json_encode($table);
//echo $jsonTable;
}
?>
</body>
</html>