generating graph with static data using Google Charts - php

I want to generate graph for my static data. I am using Google Chart for doing this. Here is the google chart code
<html>
<head>
<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([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
But i want to put my code in this. I am not getting how to do it. Here is my code
<?php
echo '<div align="center" style="width:100%; padding-top:20px;">
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td class=tddash>10 latest purchase orders</td>
</tr>
<tr>
<td>';
$SQL = 'SELECT purchorders.orderno,
suppliers.suppname,
purchorders.orddate,
purchorders.deliverydate,
purchorders.initiator,
purchorders.requisitionno,
purchorders.allowprint,
purchorders.status,
suppliers.currcode,
currencies.decimalplaces AS currdecimalplaces,
SUM(purchorderdetails.unitprice*purchorderdetails.quantityord) AS ordervalue
FROM purchorders
INNER JOIN purchorderdetails
ON purchorders.orderno = purchorderdetails.orderno
INNER JOIN suppliers
ON purchorders.supplierno = suppliers.supplierid
INNER JOIN currencies
ON suppliers.currcode=currencies.currabrev
WHERE purchorders.orderno=purchorderdetails.orderno
GROUP BY purchorders.orderno,
suppliers.suppname,
purchorders.orddate,
purchorders.initiator,
purchorders.requisitionno,
purchorders.allowprint,
purchorders.status,
suppliers.currcode,
currencies.decimalplaces LIMIT 5';
$SalesOrdersResult2 = DB_query($SQL,$db);
$Total = 0;
echo '<table width="100%" celpadding="2" class="selection">';
echo '<tbody><tr><th> Supplier </th><th>Order Date</th><th>Delivery Date</th><th>Initiator</th><th>Order Total</th><th>Status</th></tr></tbody> ';
$k=0;
while ($row = DB_fetch_array($SalesOrdersResult2))
//while ($row = mysql_fetch_array($SalesOrdersResult))
{
if ($k == 1){
echo '<tr class="EvenTableRows">';
$k = 0;
} else {
echo '<tr class="OddTableRows">';
$k = 1;
}
$FormatedOrderValue2 = locale_number_format($row['ordervalue'],$row['currdecimalplaces']);
$Total += $row['ordervalue'];
//$FormatedOrderValue1 = locale_number_format($myrow['ordervalue'],$_SESSION['CompanyRecord']['decimalplaces']);
$FormatedOrderDate1 = ConvertSQLDate($row['orddate']);
$FormatedDelDate1 = ConvertSQLDate($row['deliverydate']);
echo ' <td> ' . $row['suppname'] . ' </td>';
echo ' <td>$FormatedOrderDate1</td><td>$FormatedDelDate1</td><td> ' . $row['initiator'] . ' </td><td>$FormatedOrderValue2</td><td> ' . $row['status'] . ' </td> ';
}
echo '<tr><td colspan="3">Total---</td><td colspan="2">$Total</td></tr></tbody>';
echo '</table></td>';
echo' </tr>
</table>
</div>';
Can somebody plz help me in this?
* EDITED *
echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>';
echo ' <script type="text/javascript">
function drawChart() {
var jsonData = $.ajax({
url: "1getData.php",
dataType:"json",
async: false
}).responseText;
alert(jsonData);
var data = new google.visualization.DataTable(jsonData);
var view = new google.visualization.DataView(data);
view.setColumns([0, 3]);
var chart = new google.visualization.ColumnChart(document.getElementById("chart_div"));
chart.draw(view, {width:400, height:240});
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
</script>';
echo '</head>';
<div id="chart_div" ></div>
1getData.php
<?php
$PageSecurity=0;
include('includes/session.inc');
if (!isset($RootPath)){
$RootPath = dirname(htmlspecialchars($_SERVER['PHP_SELF']));
if ($RootPath == '/' or $RootPath == "\\") {
$RootPath = '';
}
}
$SQL = "SELECT workorders.wo, woitems.stockid, stockmaster.description, stockmaster.decimalplaces, woitems.qtyreqd, woitems.qtyrecd, workorders.requiredby, workorders.startdate
FROM workorders
INNER JOIN woitems ON workorders.wo = woitems.wo
INNER JOIN stockmaster ON woitems.stockid = stockmaster.stockid
ORDER BY workorders.wo";
$searchresult = DB_query($SQL, $db);
$table=array();
$table['cols']=array(
array('label'=>'ITEM', type=>'string'),
array('label'=>'Description', type=>'string'),
array('label'=> 'QTY Required', type=>'number'),
array('label'=>'QTY Outstanding', type=>'number')
);
$rows=array();
while ($row = DB_fetch_array($searchresult))
{
$qreq = locale_number_format($row['qtyreqd'],$row['decimalplaces']);
$qout = locale_number_format($row['qtyreqd']-$row['qtyrecd'],$row['decimalplaces']);
$temp=array();
$temp[]=array('v' => $row['stockid']);
$temp[]=array('v' => $row['description']);
$temp[]=array('v' => $row['qtyreqd']);
$temp[]=array('v' => ($row['qtyreqd']-$row['qtyrecd']));
$rows[]=array('c' => $temp);
}
$table['rows']=$rows;
$jsonTable = json_encode($table);
print $jsonTable;
?>
but it displays only two columns, where as i want to display 3
JAVA SCRIPT
<script type="text/javascript">
function drawChart() {
var jsonData = $.ajax({
url: "1getData.php",
dataType:"json",
async: false
}).responseText;
alert(jsonData);
var data = new google.visualization.DataTable(jsonData);
var view = new google.visualization.DataView(data);
view.setColumns([0,3]);
var chart = new google.visualization.ColumnChart(document.getElementById("chart_div"));
chart.draw(view, {width:400, height:240});
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
</script>

Your line view.setColumns([0, 3]) tells Google charts to only display the first and fourth column in your data. Add the columns you want to display to the array.

Related

Error while fetching MySQL data for Google Charts "Data column(s) for axis #0 cannot be of type string"

The PHP code throws the error "Data column(s) for axis #0 cannot be of type string"
<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([
['Year1', 'CountGiardiaPos', 'CountCryptoPos'],
<?php
$result = mysqli_query($connection, "SELECT * FROM sqlAnnualPositives2");
if($result){
echo "CONNECTED TO CLOUD PRU DATABASE<br>";
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array()) {
echo "[".$row[Year1].", ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
}
}
?>
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 1600px; height: 800px"></div>
</body>
</html>
If I run the code in a separate PHP file
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array()) {
echo "['".$row[Year1]."', ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
}
}
I get the correct data:
['2003', 0, 207],['2005', 0, 29],['2006', 1, 59],['2007', 1, 148],['2008', 1, 109],['2009', 72, 71],['2010', 450, 261],['2011', 1934, 967],['2012', 662, 206],['2013', 627, 487],['2014', 735, 233],['2015', 720, 350],['2016', 855, 503],['2017', 836, 593],['2018', 983, 950],['2019', 920, 508],['2020', 291, 97],
Where is the error in the code?
the issue is that you're printing "CONNECTED TO CLOUD PRU DATABASE<br>" in the middle of your data array, here...
var data = google.visualization.arrayToDataTable([ // <-- ARRAY STARTS HERE
['Year1', 'CountGiardiaPos', 'CountCryptoPos'],
<?php
$result = mysqli_query($connection, "SELECT * FROM sqlAnnualPositives2");
if($result){
// PRINTING THIS HERE WILL MESS UP YOUR ARRAY
echo "CONNECTED TO CLOUD PRU DATABASE<br>";
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array()) {
echo "[".$row[Year1].", ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
}
}
?>
]); // <-- ARRAY ENDS HERE
but let's back up. first, it is not recommended to manually build json data by concatenating strings and variables.
echo "[".$row[Year1].", ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
instead, build the array in php and use json_encode to print it on the page.
<?php
$result = mysqli_query($connection, "SELECT * FROM sqlAnnualPositives2");
$rows = array();
if ($result->num_rows > 0) {
// add column headings
$rows[] = array('Year1', 'CountGiardiaPos', 'CountCryptoPos');
// output data of each row
while($row = $result->fetch_array()) {
$rows[] = array($row[Year1], $row[CountGiardiaPos], $row[CountCryptoPos]);
}
}
?>
<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() {
// use json_encode to build data table
var data = google.visualization.arrayToDataTable(<?php echo json_encode($rows); ?>);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 1600px; height: 800px"></div>
</body>
</html>

Multi line Google Line Chart, using data from mySQL db

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>

JSON PHP Google Visualisation

Trying to get my json output in the right format for a google visualisation line chart but I am clearly doing something wrong as it is returning table has no columns. As explained in the docs I am using Ajax to call a php page.
getData.php
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('water.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
//echo "Opened database successfully\n";
}
$sql =<<<EOF
SELECT * from wT;
EOF;
$data = array();
$data['cols'][] = array('label' => 'Temperature', 'type' => 'number');
$data['cols'][] = array('label' => 'Time', 'type' => 'string');
$rows = array();
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
$temp = array();
$temp[] = array('v' => (float) $row['fishTemp']);
$temp[] = array('v' => (string) $row['time']);
$rows = array('c' => $temp);
$data['rows'][] = $rows;
}
$jsonTable = json_encode($data, true);
var_dump($jsonTable);
$db->close();
?>
base.html
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
console.log(jsonData);
//var obj = window.JSON.stringify(jsonData);
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'Title'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
The output from the console looks like this....what am I missing?!
"{"cols":[{"label":"Temperature","type":"string"},{"label":"Time","type":"date"}],"rows":[{"c":[{"v":18.25},{"v":"2014-08-19 16:23:23"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:23:31"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:23:39"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:23:47"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:23:55"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:24:06"}]},{"c":[{"v":18.25},{"v":"2014-08-19 16:24:14"}]}
Loading dataTable with json accepts dates as a string in the following format: Date(year, month, day[,hour, minute, second[, millisecond]]) where everything after day is optional, and months are zero-based.
So for your first timeStamp, it should be :
{"v":"Date(2014,07,19,16,23,23)"}
If you want to use directly the milliseconds time:
{"v":"Date(1411154603000)}

Google chart for each row of MySqL table

New PHP user here. I have a database that looks like this:
id name day1 day2 day3 day4 day5
1 nam1 5 9 15 50 45
2 nam2 51 12 54 78 56
3 nam3 12 145 78 49 58
The database contains thousands of users. Each number in the table represents the amount of daily activities per user. We need a table which looks like this
id name day1 day2 day3 day4 day5 chart
1 nam1 5 9 15 50 45
2 nam2 51 12 54 78 56
3 nam3 12 145 78 49 58
We want to draw a google line chart in the last column for each user. This is the code to generate the chart:
<?php
$result = mysqli_query($c,"SELECT * from users limit 100");
$row = mysqli_fetch_array($result);
$d1=$row['day1']; $d2=$row['day2']; $d3=$row['day3']; $d4=$row['day4']; $d5=$row['day5'];
//// that's the data that get loaded into Google Charts(no axis label) ////
$data="[['','day'],['',".$d1."],['', ".$d2."],['', ".$d3. "],['', ".$d4."],['', ".$d5. "]]";
?>
<html>
<head>
<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"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo $data ?>);
var options = {
title: 'User Activities',
curveType: 'function',
width:200,
height:150,
legend: 'none'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<?php echo "<table border='1'>
<tr>
<th>id</th>
<th>name</th>
<th>charts</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>
<div id=\"chart_div\" style=\"width:200; height:150\"></div></td>";
echo "</tr>";
}
echo "</table>"; ?>
</body>
</html>
This code generates only one chart for user id=2. The first user, and the other users are ignored. How do you get a chart for each row? Thanks four help.
The easiest way requires a bit of rearranging your code to make it work:
<html>
<head>
</head>
<body>
<table border='1'>
<tr><th>id</th><th>name</th><th>charts</th></tr>
<?php
$result = mysqli_query($c,"SELECT * from users limit 100");
$data = array(array('', 'Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'));
$i = 0;
while($row = mysqli_fetch_array($result)) {
echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td><div id='chart_div_{$i}' style='width:200; height:150'></div></td></tr>";
$data[] = array('', $row['day1'], $row['day2'], $row['day3'], $row['day4'], $row['day5']);
$i++;
}
?>
</table>
<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"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>);
var options = {
title: 'User Activities',
curveType: 'function',
width: 200,
height: 150,
legend: 'none'
};
var charts = [];
var views = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
views.push(new google.visualization.DataView(data));
views[i].setRows([i]);
charts.push(new google.visualization.LineChart(document.querySelector('#chart_div_' + i)));
charts[i].draw(views[i], options);
}
}
</script>
</body>
</html>
That won't produce very nice LineCharts, however, as you will have 5 lines with 1 point each. If you are looking for a single line that spans 5 days, then this is how you want to set it up:
<html>
<head>
</head>
<body>
<table border='1'>
<tr><th>id</th><th>name</th><th>charts</th></tr>
<?php
$result = mysqli_query($c,"SELECT * from users limit 100");
$data = array(
array('Day'),
array('Day 1'),
array('Day 2'),
array('Day 3'),
array('Day 4'),
array('Day 5')
);
$i = 0;
while($row = mysqli_fetch_array($result)) {
echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td><div id='chart_div_{$i}' style='width:200; height:150'></div></td></tr>";
$data[0][] = "Daily activities for {$row['name']}";
$data[1][] = $row['day1'];
$data[2][] = $row['day2'];
$data[3][] = $row['day3'];
$data[4][] = $row['day4'];
$data[5][] = $row['day5'];
$i++;
}
?>
</table>
<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"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>);
var options = {
title: 'User Activities',
curveType: 'function',
width: 200,
height: 150,
legend: 'none'
};
var charts = [];
var views = [];
for (var i = 0; i < data.getNumberOfColumns() - 1; i++) {
views.push(new google.visualization.DataView(data));
views[i].setColumns([0, i + 1]);
charts.push(new google.visualization.LineChart(document.querySelector('#chart_div_' + i)));
charts[i].draw(views[i], options);
}
}
</script>
</body>
</html>

Google Visualization Column Chart - How to make labels as currency

I'm just trying to figure out to format my labels to be shown as a currency and not just a number:
echo ' <script type="text/javascript" src="http://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();
data.addColumn("string", "ZipCode");
data.addColumn("number", "Sales");
data.addRows('.$count.');';
$i = 0;
foreach ($results as $r) {
$p = (($r->report_trans_amount / $total) * 100);
$pd = strval(number_format($p, 1));
echo ' data.setValue(' . $i . ', 0, "' . $r->member_address_zip_code .
' - ' . $pd . '%");';
echo ' data.setValue(' . $i . ', 1, ' . $r->report_trans_amount . ');';
$i++;
}
echo ' var chart = new google.visualization.PieChart(
document.getElementById("chart_div"));
chart.draw(data, {width:900, height:500, is3D:true});
}
</script>
<div id="chart_div"></div>
';
I would like the Sales column to be shown as a USD currency value. How can I do that? I see how to do it using the URL request, but that does not help this situation.
I just can't seem to find any good example on this.
it looks like you might want to look at setFormattedValue
http://code.google.com/apis/chart/interactive/docs/reference.html#DataTable_setFormattedValue
and for the format stuff look at
http://code.google.com/apis/chart/interactive/docs/reference.html#formatters
I haven't tried this out, but from what I can tell this could work for you:
echo '
<script type="text/javascript" src="http://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();
data.addColumn("string", "ZipCode");
data.addColumn("number", "Sales");
data.addRows('.$count.');
var formatter = new google.visualization.NumberFormat({prefix: \'$\'});
formatter.format(data, 1);';
$i = 0;
foreach($results as $r){
$p = (($r->report_trans_amount / $total) * 100);
$pd = strval(number_format($p, 1));
echo 'data.setValue('.$i.', 0, "'.$r->member_address_zip_code.' - '.$pd.'%");';
//echo 'data.setFormattedValue('.$i.', 1, formatter);'; // might not need this with the formatter.format above
echo 'data.setValue('.$i.', 1, '.$r->report_trans_amount.');';
$i++;
}
echo ' var chart = new google.visualization.PieChart(document.getElementById("chart_div"));
chart.draw(data, {width:900, height:500, is3D:true});
}
</script>
<div id="chart_div"></div>
';
references:
http://code.google.com/p/google-visualization-api-issues/issues/detail?id=282

Categories