load mysql data to google chart in PHP - php

could you please help here. Below is the script that am using to get the MYSQL data and pass that to google chart
$result = DB_query($sql, '', '', False, False);
$table = array();
$table['cols'] = array(
array('label' => 'col1', 'type' => 'string'),
array('label' => 'col2', 'type' => 'int')
);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$temp = array();
// the following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['col1']);
// Values of each slice
$temp[] = array('v' => (int) $r['col2']);
$rows[] = array('c' => $temp);
}
Below is the js part
echo
'
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {"packages":["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(',$jsonTable,');
var options = {
title: "My Weekly Plan",
is3D: "true",
width: 800,
height: 600
};
var chart = new google.visualization.PieChart(document.getElementById("chart_div"));
chart.draw(data, options);
}
</script>
<div id="chart_div"></div>
';
the problem here is even though am getting the correct value in the JSON variable, while loading the same to google chart am getting below error and hence the chart is not getting displayed.
"Uncaught Error: Invalid type, int, for column "col2".
at gvjs_R.gvjs_.Sda
Could you please help in understanding this issue.

change 'int' to 'number'
valid types for google data table...
type - A string with the data type of the values of the column. The type can be one of the following: 'string', 'number', 'boolean', 'date', 'datetime', and 'timeofday'
see DataTable addColumn

Related

Google charts with two series on charts (SQL/PHP)

I trying build the charts with API google charts and i'am very lost... I have a database on PhpMyAdmin where there are 2 columns : numberPeople and date.
So, I would like to display on the chart, the number of people for year N and an other lines with year N-1...
But I don't understand.
Could you help me? I put to you in appendix what I have make
<?php
$pdoSynchro = new PDO("mysql:dbname=store17;host=localhost","root","");
$date_now = date("Y");
$date_old = date("Y")-1;
$anneeN = $pdoSynchro->query('SELECT nombrePersonne, date FROM compteur_client WHERE YEAR(date) ='.$date_now);
$anneeN1 = $pdoSynchro->query('SELECT nombrePersonne, date FROM compteur_client WHERE YEAR(date) ='.$date_old);
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles
// Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
array('label' => 'Date', 'type' => 'string'),
array('label' => 'Nbr de personne en '.$date_now, 'type' => 'number'),
array('label' => 'Nbr de personne en '.$date_old, 'type' => 'number')
);
$rows = array();
while ($r = $anneeN->fetch()) {
$temp = array();
$temp[] = array('v' => $r['date']);
$temp[] = array('v' => (int) $r['nombrePersonne']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
var_dump($jsonTable);
//echo $jsonTable;
?>
<html>
<head>
<!--Load the Ajax API-->
<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">
// Load the Visualization API and the piechart package.
google.charts.load('current', {packages: ['corechart', 'bar']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.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: 'Nombre de clients par jour',
width: 1000,
height: 500,
};
// Do not forget to check your div ID
var chart = new google.visualization.LineChart(document.getElementById('linechart_material'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="linechart_material"></div>
</body>
</html>
<?php
$pdoSynchro = new PDO("mysql:dbname=store17;host=localhost","root","");
$query = $pdoSynchro->query("SELECT date, nombrePersonne FROM compteur_client"); // select column
?>
<!DOCTYPE html>
<html>
<head>
<title>Massive Electronics</title>
<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();
var data = google.visualization.arrayToDataTable([
['Date','Nombre client par jour'],
<?php
while($row = $query->fetch()){
echo "['".$row["date"]."', ".$row["nombrePersonne"]."],";
}
?>
]);
var options = {
title: 'Nombre client/J',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.AreaChart(document.getElementById('areachart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="areachart" style="width: 900px; height: 400px"></div>
</body>
</html>
For the result of my JSON data ( it's part of data because, not all data is not displayed ) :
'{"cols":[
{"label":"Date N","type":"string"},
{"label":"Nbr de personne en 2018","type":"number"},
{"label":"Nbr de personne en 2017","type":"number"}],
"rows":[
{"c":[{"v":"2017-07-05 00:00:00.000000"},{"v":null},{"v":10}]},
{"c":[{"v":"2017-07-21 00:00:00.000000"},{"v":null},{"v":15}]},
{"c":[{"v":"2017-07-22 00:00:00.000000"},{"v":null},{"v":12}]},
{"c":[{"v":"2017-07-23 00:00:00.000000"},{"v":null},{"v":13}]},
{"c":[{"v":"2017-07-19 00:00:00.000000"},{"v":null},{"v":15}]},
{"c":[{"v":"2017-07-19 00:00:00.000000"}'
THANK YOU VERY MUCH FOR YOU'RE HELP 100000x THANK YOU !!!
EDIT
AND RESULT OF JSON :
{"cols":[
{"label":"Date","type":"date"},
{"label":"Nbr de personne en 2018","type":"number"},
{"label":"Nbr de personne en 2017","type":"number"}],
"rows":[
{"c":[{"v":"Date(2018, -1, , , , )","f":"2017--"},{"v":null},{"v":10}]},
{"c":[{"v":"Date(2018, -1, , , , )","f":"2017--"},{"v":null},{"v":15}]},
{"c":[{"v":"Date(2018, -1, , , , )","f":"2017--"},{"v":null},{"v":12}]},
{"c":[{"v":"Date(2018, -1, , , , )","f":"2017--"},{"v":null},{"v":13}]},
{"c":[{"v":"Date(2018, -1, , , , )","f":"2017--"},{"v":null},{"v":15}]}'
and i have a message : 'a.getTime' is not a function.
since you have two different queries, you'll need to load separate rows for each,
but you still need to populate both columns...
just use null in the column not being used in the query,
as such...
// old date
while ($r = $anneeN1->fetch()) {
$temp = array();
$temp[] = array('v' => $r['date']);
$temp[] = array('v' => null);
$temp[] = array('v' => (int) $r['nombrePersonne']);
$rows[] = array('c' => $temp);
}
// now date
while ($r = $anneeN->fetch()) {
$temp = array();
$temp[] = array('v' => $r['date']);
$temp[] = array('v' => (int) $r['nombrePersonne']);
$temp[] = array('v' => null);
$rows[] = array('c' => $temp);
}
note: probably makes sense to load old first, so dates are in correct order...
EDIT
to compare for year over year, first, we will need to use real dates, not strings...
change the first column from 'string' to 'date'...
array('label' => 'Date', 'type' => 'date'),
here...
$table = array();
$table['cols'] = array(
array('label' => 'Date', 'type' => 'date'),
array('label' => 'Nbr de personne en '.$date_now, 'type' => 'number'),
array('label' => 'Nbr de personne en '.$date_old, 'type' => 'number')
);
next, the dates will need to be in the same year on the x-axis,
so we need to change the old date to the current year.
but, we can use the formatted value to display the real date in the tooltip...
'v' = value, 'f' = formatted value
we can use google's json date string to pass real dates --> "Date(y, m, d, h, n, s)"
so in the "old" routine, we create the date using the current year,
and provide the real date in the formatted value,
then format the "now" dates the same way...
// old date
while ($r = $anneeN1->fetch()) {
// value - old date converted to now year
$rowDate = "Date(".$date_now.", ".((int) date_format($r['date'], 'm') - 1).", ".date_format($r['date'], 'd').", ".date_format($r['date'], 'H').", ".date_format($r['date'], 'i').", ".date_format($r['date'], 's').")";
// formatted value - real value
$rowStr = $date_old."-".date_format($r['date'], 'm')."-".date_format($r['date'], 'd');
$temp = array();
$temp[] = array('v' => $rowDate, 'f' => $rowStr); // <-- use formatted value for real date
$temp[] = array('v' => null);
$temp[] = array('v' => (int) $r['nombrePersonne']);
$rows[] = array('c' => $temp);
}
// now date
while ($r = $anneeN->fetch()) {
$rowDate = "Date(".$date_now.", ".((int) date_format($r['date'], 'm') - 1).", ".date_format($r['date'], 'd').", ".date_format($r['date'], 'H').", ".date_format($r['date'], 'i').", ".date_format($r['date'], 's').")";
$rowStr = $date_now."-".date_format($r['date'], 'm')."-".date_format($r['date'], 'd');
$temp = array();
$temp[] = array('v' => $rowDate, 'f' => $rowStr);
$temp[] = array('v' => (int) $r['nombrePersonne']);
$temp[] = array('v' => null);
$rows[] = array('c' => $temp);
}
to show the month abbreviation on the x-axis, add this to your chart options...
hAxis: {format: 'MMM'}
EDIT 2
need to convert date string from query to real date, see --> $realDate
// old date
while ($r = $anneeN1->fetch()) {
$realDate = date_create($r['date']);
// value - old date converted to now year
$rowDate = "Date(".$date_now.", ".((int) date_format($realDate, 'm') - 1).", ".date_format($realDate, 'd').", ".date_format($realDate, 'H').", ".date_format($realDate, 'i').", ".date_format($realDate, 's').")";
// formatted value - real value
$rowStr = $date_old."-".date_format($realDate, 'm')."-".date_format($realDate, 'd');
$temp = array();
$temp[] = array('v' => $rowDate, 'f' => $rowStr);
$temp[] = array('v' => null);
$temp[] = array('v' => (int) $r['nombrePersonne']);
$rows[] = array('c' => $temp);
}
// now date
while ($r = $anneeN->fetch()) {
$realDate = date_create($r['date']);
$rowDate = "Date(".$date_now.", ".((int) date_format($realDate, 'm') - 1).", ".date_format($realDate, 'd').", ".date_format($realDate, 'H').", ".date_format($realDate, 'i').", ".date_format($realDate, 's').")";
$rowStr = $date_now."-".date_format($realDate, 'm')."-".date_format($realDate, 'd');
$temp = array();
$temp[] = array('v' => $rowDate, 'f' => $rowStr);
$temp[] = array('v' => (int) $r['nombrePersonne']);
$temp[] = array('v' => null);
$rows[] = array('c' => $temp);
}

One or more participants failed to draw(), Invalid Column Label

I have an error that looks like this when I tried to insert a number range filter for my pie chart
One or more participants failed to draw()
Invalid column label:percentage
How it look likes and there's no error message in the console
I tried to make it look exactly like the example they provided in https://developers.google.com/chart/interactive/docs/gallery/controls with the only difference in data. The data used in the example is hard-coded while the data I used is directly from MySQL using PHP.
Here is my PHP codes.
<?php
$con=mysqli_connect("localhost","root","password") or die("Failed to connect with database");
mysqli_select_db($con, "tutor");
$sql="SELECT *
FROM googlechart";
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
$rows = array();
$flag = true;
$table = array();
$table['cols'] = array(
array('label' => 'Topics', 'type' => 'string'),
array('label' => 'Percentage', 'type' => 'number')
);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$temp = array();
$temp[] = array('v' => (string) $r['weekly_task']);
$temp[] = array('v' => (int) $r['percentage']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
?>
<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', 'controls']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard_div'));
var donutRangeSlider = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'filter_div',
'options': {
'filterColumnLabel': 'percentage'
}
});
var pieChart = new google.visualization.ChartWrapper({
'chartType': 'PieChart',
'containerId': 'chart_div',
'options': {
'width': 300,
'height': 300,
'pieSliceText': 'value',
'legend': 'right'
}
});
dashboard.bind(donutRangeSlider, pieChart);
dashboard.draw(data);
}
</script>
</head>
<body>
<div id="dashboard_div">
<div id="filter_div"></div>
<div id="chart_div"></div>
</div>
</body>
Please advice. Thank you in advance.
The problem lies in the donutRangeSlider's filterColumnLabel.
var donutRangeSlider = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'filter_div',
'options': {
'filterColumnLabel': 'percentage'
}
});
Instead of naming it as 'percentage', it should be 'Percentage' as follow in the PHP code's column label.
$table['cols'] = array(
array('label' => 'Topics', 'type' => 'string'),
array('label' => 'Percentage', 'type' => 'number')
);
Solution:
var donutRangeSlider = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'filter_div',
'options': {
'filterColumnLabel': 'Percentage'
}
});

How to draw a google line chart using the below code?

I want to draw a line chart using "Google Charts" tools. I'm fetching the data required for the line chart from the MySql database. The code for it is as below:
<?php
require_once('../includes/public-application-header.php');
$con=mysql_connect("localhost","root","eywaadmin") or die("Failed to connect with database!!!!");
mysql_select_db("OCN", $con);
$sql =" SELECT DATE_FORMAT( FROM_UNIXTIME( transaction_date ) , '%d/%m/%Y') 'transaction_date', COUNT(*) 'total count', SUM(transaction_status = 'success') ";
$sql .=" success, SUM(transaction_status = 'inprocess') inprocess, SUM(transaction_status = 'fail') fail, ";
$sql .=" SUM(transaction_status = 'cancelled') cancelled FROM user_transaction WHERE ";
$sql .=" transaction_date >= 1325376000 AND transaction_date <= 1373846400 GROUP BY date(FROM_UNIXTIME(transaction_date)) ";
$r= mysql_query($sql) or die(mysql_error());
$transactions = array();
while($result = mysql_fetch_array($r, MYSQL_ASSOC)){
$transactions[] = $result;
}
$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles
// Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
array('label' => 'Transaction Date', 'type' => 'string'),
array('label' => 'Total Count', 'type' => 'number'),
array('label' => 'Success', 'type' => 'number'),
array('label' => 'Inprocess', 'type' => 'number'),
array('label' => 'Failed', 'type' => 'number'),
array('label' => 'Cancelled', 'type' => 'number'),
);
$rows = array();
foreach($transactions as $tr) {
$temp = array();
foreach($tr as $key=>$value){
// the following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $key);
// Values of each slice
$temp[] = array('v' => (int) $value);
}
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<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: 'User Transaction Statistics',
is3D: 'true',
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.LineChart(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>
I want to put the dates(i.e. transaction_date) on X-axis and Count values(i.e.10,20,30,40) from on Y-axis. But unfortunately I'm not getting the line chart in the desired format. I'm attaching the screen shot of what I got after executing the above code.
Can anyone please help me in this regard? Thanks in advance. If you want any further information I can add it to the question body.
As per the request from jmac I'm posting the json response created for your reference. If you still need ny other thing like the query output, etc. I can provide you. The screenshot of the line -chart is attached.
The main problem is that you are saving the column names as well as the column values in the data set. You should just be storing the values.
$temp = array();
foreach($tr as $key=>$value){
// Values of each slice
$temp[] = array('v' => (int) $value);
}
$rows[] = array('c' => $temp);
The second problem is that you are converting all the values to ints. If you want the date to display as an actual date, you should get rid of that conversion.
$temp = array();
foreach($tr as $key=>$value){
// Values of each slice
$temp[] = array('v' => $value);
}
$rows[] = array('c' => $temp);
I have no idea how your jsonTable looks like, but it should be formatted in this way:
['transaction date', 'Total count', 'Succes', 'In progress', 'Failed', 'Canceled'],
['19-7-2013', 50, 40, 5, 2, 3],
['20-7-2013', 60, 50, 5, 1, 4],
['21-7-2013', 50, 40, 5, 2, 3],
['22-7-2013', 60, 50, 5, 1, 4],
['23-7-2013', 50, 40, 5, 2, 3]
Are you able to send me your $jsonTable?
This link shows you an example of the table: http://jsfiddle.net/kxd2u/
I don't think you have a issue with the amount of data. I made some charts myself with a lot of data and all working fine!
You are inputting your data incorrectly. Try this:
foreach ($transactions as $tr) {
$temp = array();
$temp[] = array('v' => $tr['transaction_date']);
$temp[] = array('v' => (int) $tr['total count']);
$temp[] = array('v' => (int) $tr['success']);
$temp[] = array('v' => (int) $tr['inprocess']);
$temp[] = array('v' => (int) $tr['fail']);
$temp[] = array('v' => (int) $tr['cancelled']);
$rows[] = array('c' => $temp);
}
This will produce a chart with a discrete axis, where each row of data is evenly spaced on the chart, regardless of the distance between dates. If you want a continuous axis (see this as an example of the difference between discrete and continuous), you have to format your dates a bit differently:
in the columns:
array('label' => 'Transaction Date', 'type' => 'date')
in the rows:
$dateArray = explode('/', $tr['transaction_date']);
$year = $dateArray[2];
$month = $dateArray[1] - 1; // need to subtract 1 to convert to javascript month format
$day = $dateArray[0];
$temp[] = array('v' => "Date($year, $month, $day)", f: $tr['transaction_date']);
You can then format the date axis in the chart's options:
hAxis: {
format: 'd/M/yyyy'
}
As an aside, you can get rid of that $flag variable in PHP - it is an artifact left over from the original code that I posted as an example a long time ago in the Google Visualization API group. It keeps cropping up whenever that code gets copied, and no one ever deletes it.

How to query MySQL with a PHP variable and have the results displayed via Google Charts?

I am just getting started using the Google Charts API with PHP and MySQL and would love a little assistance. I would like the results of a MySQL query that Google Charts uses to be based off of a variable. Basically I have this and it works as expected.
displayChart.php
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', { packages: ['corechart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "test3.php",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var options = {
fontName: 'Trebuchet MS',
colors: ['#22671F'],
title: 'Handicap History',
hAxis: {title: 'Revision Date', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
test3.php
$result = $connect->query("SELECT rev_date, ndx FROM revisions WHERE player_id=7");
$table = array();
$table['cols'] = array(
array('label' => 'Rev', 'type' => 'string'),
array('label' => 'Index', 'type' => 'number')
);
$rows = array();
while ($nt = $result->fetch_assoc())
{
$temp = array();
$temp[] = array('v' => $nt['rev_date']);
$temp[] = array('v' => $nt['ndx']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
I'd like to be able to do something like this in test3.php
$result = $connect->query("SELECT rev_date, ndx FROM revisions WHERE player_id='$playerID'");
$table = array();
$table['cols'] = array(
array('label' => 'Rev', 'type' => 'string'),
array('label' => 'Index', 'type' => 'number')
);
$rows = array();
while ($nt = $result->fetch_assoc())
{
$temp = array();
$temp[] = array('v' => $nt['rev_date']);
$temp[] = array('v' => $nt['ndx']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
How can I pass a value for the $playerID variable to the test3.php page? Can I pass a variable when the url: "test3.php" piece is called in the ajax and use a $_GET on test3.php? Or is there another way of doing this?
Thank you so much in advance.
In the $.ajax() method, you can use the data property in the options.
Example:
var jsonData = $.ajax({
url: "test3.php",
dataType: "json",
async: false,
data: { 'playerID' : 123 }
}).responseText;
Following up on my comment to your question regarding SYNC commands... you should use the callback methods available to fire the next function.
You can use test3.php?player=your_id and use $playerid = (int)$_GET['player']; to get the param from the url

Getting JSON from MySQL into Google Charts

I'm trying to populate a basic Google Area Chart using their example and some data from a MySQL table. Here's what I have:
<?php
include("inc/DBConn.php");
$link = connectToDB();
$query = "SELECT MONTH(checkout) as Checkout, COUNT(item_id) as BookCount FROM C_books WHERE YEAR(checkout) = 2012 GROUP BY MONTH(created) ASC";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$numBooks[] = $row;
};
$chartData = json_encode($numBooks,JSON_NUMERIC_CHECK);
?>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo $chartData; ?>,false);
var options = {
title: 'Total Books',
hAxis: {title: 'Month', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
This is my result with the echo:
[{"Checkout":"3","BookCount":"19"},{"Checkout":"4","BookCount":"157"},{"Checkout":"5","BookCount":"30"},{"Checkout":"6","BookCount":"45"},{"Checkout":"7","BookCount":"688"},{"Checkout":"8","BookCount":"391"}]
I know that Google doesn't like this but I'm unable to understand how to format it so that it does???
$numBooks[] = array("Checkout", "BookCount");
while ($row = mysql_fetch_array($result)) {
$numBooks[] = $row;
};
present data in needed format
the following is my method of using SQL -> Array -> Google DataTable JSON String (I have not referenced how others do it, so there could be a better way of coding it). Note that $task_submissions_arr is an array populated with rows & columns from a database query (but not shown below)
<?php
// array to be converted to json string and used in google chart's bar chart
$bar_chart_cols_arr = array(
array('id' => 'Name', 'label' => 'Name', 'type' => 'string'),
array('id' => 'Auto Grading Marks', 'label' => 'Auto Grading Marks', 'type' => 'number'),
array('id' => 'Manual Grading Marks', 'label' => 'Manual Grading Marks', 'type' => 'number'));
// array to be converted to json string and used in google chart's bar chart
$bar_chart_rows_arr = array();
for($i=0; $i<count($task_submissions_arr); $i++){
// array nesting is complex owing to to google charts api
array_push($bar_chart_rows_arr, array('c' => array(
array('v' => $task_submissions_arr[$i]['name']),
array('v' => $task_submissions_arr[$i]['auto_grading_marks']),
array('v' => $task_submissions_arr[$i]['manual_grading_marks']))) );
}
?>
<script type="text/javascript">
google.setOnLoadCallback(draw_bar_chart);
function draw_bar_chart() {
var bar_chart_data = new google.visualization.DataTable(
{
cols: <?php echo json_encode($bar_chart_cols_arr); ?>,
rows: <?php echo json_encode($bar_chart_rows_arr); ?>
});
// to be continued...
</script>

Categories