Google Charts - Put data by PHP echo - javascript

I`m trying put to google charts data by PHP echo (from the database). But charts show only one row from DB. Where I do a mistake? How to make charts to get data from all rows?
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Orders');
data.addRows([
['<?php echo $rowb[0];?>', <?php echo $rowb[1];?>],
]);
// Set chart options
var options = {'title':'Orders',
'width':1000,
'height':250};

Try this
<?php
$data = [];
for($i = 0; $i< count($rowb); $i+2) {
array_push($data, [$rowb[$i], $rowb[§i+1]]);
}
?>
data.addRows(<?php echo json_encode($data) ?>);

Related

How to populate google visualization data table from MySQL database with PHP?

```
<?php
// open database connection
$connection = mysqli_connect('localhost', '', '');
// sql query
$result = mysql_query($connection, "SELECET name, author, publisher, yearOfPublish, ISBN
FROM books");
if(!$connection) {
die("Connection failer: " . mysqli_connect_error());
}
echo "Connected Succes";
?>
// html code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Main Page</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(drawTable);
// draw table function
function drawTable() {
var data = new google.visualization.DataTable();
// add columns
data.addColumn('string', 'Name');
data.addColumn('string', 'Author');
data.addColumn('string', 'Publisher');
data.addColumn('number', 'Year Of Publish');
data.addColumn('number', 'ISBN');
// add rows
data.addRows([
// retrieve data from database
]);
...
```
I have a database where I keep book information, and I am trying to retrieve those book information and put them into a google data table. I successfully opened connection with the database. However, I do not know how I am going to execute the query and get the data from the database.
function drawTable() {
var data = google.visualization.arrayToDataTable([
['Title', 'Author', 'Publisher', 'Year Of Publish', 'ISBN'],
<?php while ($row = mysqli_fetch_array($result)) {?>
['<?php echo $row['name']?>' , '<?php echo $row['author']?>', '<?php echo $row['publisher']?>', '<?php echo $row['yearOfPublish']?>', '<?php echo $row['ISBN']?>'],
<?php } ?>
]);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {showRowNumber: true, width: '50%', height: '50%'});
}
I found a solution

Issue in populating Google GeoChart Map from a PHP array in Javascript

I have a PHP array of country names -
<?php
$countries_array = array("Russia", "Australia", "Chile");
?>
I need to show these countries on map via the Google Geochart map in Javascript and using this code -
function drawRegionsMap() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
<?php
foreach ($countries_array as $cty) {
echo "data.addRow(['Country', " . $cty . "]);";
}
?>
var options = {backgroundColor: '#E7F2F4'};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
I guess I'm passing the countries array in a wrong way, because the map doesn't show these countries.
How can I correct it ?
Note PHP serves $countries_array so you need to be within PHP script tags to output the array. It is probably easier to add each data using addRow(), it makes the syntax simpler.
function drawRegionsMap() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
<?php
foreach ($countries_array as $cty) {
print "data.addRow(['" . $cty . "']);" . PHP_EOL;
}
?>
var options = {backgroundColor: '#cccccc'};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}

Cannot read property 'DataTable' of undefined in google charts

as the title saying im getting this error when trying to get charts inside function in another file like this
functions.php
function get_likes($catid){
require dirname (__FILE__).'/dbfunction.php';
?>
<script type="text/javascript" src="../assets/js/charts_min.js"></script>
<script type="text/javascript" src="../assets/js/functions.js"></script>
<?php
/// myquery here fetching the likes from database
?>
<script>
google.charts.load('current', {'packages':['corechart']});
</script>
<?php
if ($polls->execute()) {
while ($row = $polls->fetch(PDO::FETCH_ASSOC)) {
?>
<script>
a= <?php echo 2; ?> ;
b= <?php echo 3; ?> ;
c= <?php echo 5; ?> ;
i= <?php echo $row['id']; ?> ; ///// this i is looped to id 31 and 32
google.charts.setOnLoadCallback(function() { drawChart(a,b,c,i)}); ////But this didnt loop and it prints one chart for id 31. Because when i make alert(i) inside drawChart it alerts two times 31 and 31 .
</script>
<?php
echo "<div id="Votes_container"></div>";
}
}
my functions.js
function drawChart(a,b,c,i) {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['do', a],
['ri', b],
['me', c]
]);
// Set chart options
var options = {'title':'',
'width':500,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('Votes_container'+i));
chart.draw(data, options);
}
my index.php
require 'includes/functions.php';
$id = 1 ;
get_likes($catid) ;
So when i load index.php i want to get charts which gets data from database and come with get_likes() function , but my try didnt realise and it throws the error in the title .
where did the mistake located . Please ask me if i forget something before downvoting :) .
thanks for the help .
EDIT: i have edited the id of the divs where it should load the charts but it doesnt work either and same error.
Edited as the comment suggested and it prints the chart but its not looped now throw all ids.
Last Edit : this edit im writing how it worked for me.
I had to declare variables inside the function ,
google.charts.setOnLoadCallback(function() {
a= <?php echo 2; ?> ;
b= <?php echo 3; ?> ;
c= <?php echo 5; ?> ;
i= <?php echo $row['id']; ?> ;
drawChart(a,b,c,i)});

How to pass variables from while loop of PHP to JavaScript?

I'm creating one Graph chart using Google APIs I used Java Script source from Google. In PHP I'm using while loop where I fetch some array row using query, this mysql query works fine, and values of fetched array are also correct (When I echoed that in PHP) but problem is that how do I pass this values to JavaScripts function?
My PHP code is as follows :
while ($graph_result = mysqli_fetch_row($graph))
{
$graphCount = $graph_result[0];
$graphMonth = $graph_result[1];
echo $graphCount; // This works
echo $graphMonth;
}
This gives me in result of two rows, each contains two values listed below:
Now I want to pass this above values to Java script function so that it draws Graph chart for me, my javascript code is as follows:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[graphMonth, graphCount] // Here I have to place PHP values !
]);
}
So how to pass this values to JS ???
Try the below code,
In PHP
$i = 0;
while ($graph_result = mysqli_fetch_row($graph))
{
$graph_values[$i]["count"] = $graph_result[0];
$graph_values[$i]["month"] = $graph_result[1];
$i++;
}
In script,
<script>
<?php foreach($graph_values as $key){ ?>
drawChart('<?php echo $key["count"]; ?>', '<?php echo $key["month"]; ?>');
<?php } ?>
function drawChart(graphCount, graphMonth) {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[graphMonth, graphCount]
]);
}
</script>
<?php while ($graph_result = mysqli_fetch_row($graph))
{
?>
<script>
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[<?php echo $graph_result[0]; ?>, <?php echo $graph_result[1]; ?>]
]);
}
</script>
<?php
}
?>
I don't know if it is best practice or not..
You can use json to do that.
In your while loop, build an associative array and encode it in json:
$jsonArray = array();
while ($graph_result = mysqli_fetch_row($graph))
{
$graphCount = $graph_result[0];
$graphMonth = $graph_result[1];
$jsonArray[] = array($graphCount, $graphMonth);
}
echo '<div id="json">' . json_encode($jsonArray) . '</div>';
And then recover it in your javascript:
var json_data = JSON.parse(document.getElementById('json').innerHTML);
function drawChart(json_data) {
var data = google.visualization.DataTable();
data.addColumn('number','Months');
data.addColumn('number','users');
data.addRows(json_data);
}

AddRows receiving PHP Array

I'm strugling getting data from PHP into a graph. I have the following pieces of code on 1 php page. First the simple part:
$sql = "SELECT * FROM (SELECT timestamp, CurrentKelvin, TargetKelvin, WeatherTempKelvin FROM `rawdata` ORDER BY `rawdata`.`timestamp` DESC LIMIT 10) AS ttbl ORDER BY `timestamp` ASC;";
$results = mysqli_query($con,$sql);
$ChartData = array();
foreach($results as $result)
{
$ChartData[] = array( (int)$result['CurrentKelvin'],(int)$result['TargetKelvin']);
}
$ChartData = json_encode($ChartData);
Then the javascript part:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'CurrentKelvin');
data.addColumn('number', 'TargetKelvin');
alert( <?php echo json_encode($ChartData); ?>);
data.addRows( <?php echo json_encode($ChartData); ?> );
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data);
}
</script>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
When i run the above the alert command shows the following output:
[[292,290],[292,290],[291,290],[291,290],[291,290],[291,290],[291,290],[291,290],[291,290],[291,290]]
But the data.addRows line generates the following error:
Error: Argument given to addRows must be either a number or an array
Changing the data.addRows to something simple (and changing data.addColumn to string, with the same array construction, I do get a graph:
data.addRows([
['Ivan', 5],
['Igor', 7],
['Felix', 8],
['Bob', 4]
]);
I just can't figure out what is going wrong. Any help is appreciated.
Answer given by Dinesh worked:
var json_arr = <?php echo json_encode($ChartData); ?>;
data.addRows(JSON.parse(json_arr));

Categories

Resources