Multi line Google Line Chart, using data from mySQL db - php
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>
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>
How to iterate database values by date for google charts
I have seen similar questions but still do not understand how it woks.. I have this while loop looping my DB for dates, leads and sold. For each date in the DB I would like to show the daily leads and sold for each date in the DB in a line chart. $sql = "SELECT * FROM customers WHERE source = 'website' ORDER BY date ASC"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $sold = $row['sold']; $visit= $row['visit']; $date= $row['date']; }else{ } } Here is the chart script - <script type="text/javascript"> google.charts.setOnLoadCallback(drawChartl); function drawChartl() { var data = google.visualization.arrayToDataTable([ ['Date', 'Leads', 'Sold'], ['1st', 6, 2], ['2nd', 3, 1], ['3rd', 2, 3], ]); var options = { title: 'Internet Performance', curveType: 'function', legend: { position: 'top' } }; var chart = new google.visualization.LineChart(document.getElementById('curve_chart')); chart.draw(data, options); } </script> <div id="curve_chart" style="width: 1900px; height: 500px"></div>
see following snippet... need an array that holds all the data --> $json then add each row to $json --> $dataRow then write the result to the javascript --> data.addRows(<?= $jsonstring ?>); try something like this, probably need to format the date too... <?php $json = array(); $sql = "SELECT * FROM customers WHERE source = 'website' ORDER BY date ASC"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $dataRow = array( $row['date'], $row['visit'], $row['sold'] ); array_push($json, $dataRow); } } $jsonstring = json_encode($json); ?> <script src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', { 'callback': function () { var data = google.visualization.arrayToDataTable([ [{type: 'string', label: 'Date'}, {type: 'number', label: 'Leads'}, {type: 'number', label: 'Sold'}] ]); data.addRows(<?= $jsonstring ?>); var options = { title: 'Internet Performance', curveType: 'function', legend: { position: 'top' } }; var chart = new google.visualization.LineChart(document.getElementById('curve_chart')); chart.draw(data, options); }, 'packages': ['corechart'] }); </script> <div id="curve_chart" style="width: 1900px; height: 500px"></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>
Exact value not showing in google chart
I am using this code to call data from mysql and display it as a pie chart. But the chart not showing the exact value from column, whereas its showing as a percentage. I want to display the exact value. This is my code <?php $con=mysql_connect("localhost","pramir_feedback","feedback") or die("Failed to connect with database!!!!"); mysql_select_db("pramir_feedback", $con); $sth = mysql_query("SELECT * FROM average"); $rows = array(); $flag = true; $table = array(); $table['cols'] = array( array('label' => 'data', 'type' => 'string'), array('label' => 'average', 'type' => 'number') ); $rows = array(); while($r = mysql_fetch_assoc($sth)) { $temp = array(); $temp[] = array('v' => (string) $r['data']); $temp[] = array('v' => (int) $r['average']); $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: 'Average Data', 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.PieChart(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">fgfgfgfhiefkefejkfwefhfwjkefewfwf</div> </body> </html> Here you can see the chart http://innovatrix.co.in/feedback_priyajit/graph.php Thanks.
You need to ad the pieSliceText paramater, which takes the following values 'percentage','value','label' and 'none' var options = { title: 'Average Data', is3D: 'true', width: 800, height: 600, pieSliceText : 'value'}; For more details , click here https://developers.google.com/chart/interactive/docs/gallery/piechart#Configuration_Options