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

```
<?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

Related

Dynamic google line chart not showing up with php and Javascript

I am using google charts to display a line graph on my locally hosted web page. I am using mysqli to take the data from my phpmyadmin database then echoing this into the row spaces in the javascript.
This is the code within my html body:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<script>
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Speed');
data.addRows([
<?php
$sql = "SELECT id_rides, speed, date_completed FROM rides_done WHERE (id_users = $_SESSION[id])";
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_assoc($result)) {
$date = $row['date_completed'];
$speed = floatval($row['speed']);
echo "['".$date."', ".$speed."],";
}
?>
]);
var options = {
hAxis: {
title: 'Ride date'
},
vAxis: {
title: 'Average speed'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
The problem is that nothing is being displayed on the web page.
I know that the query works as I tried this on it's own outside of the javascript and this was output: results of sql query
Before I added the dynamic element of the chart it was working fine with just random lists of data.
I was expecting to see a line graph with 'Average Speed' on the y-axis and 'Ride date' on the x-axis with 7 datapoints but nothing was displayed.
It seems that js is particular about datatypes here so I'm wondering if it is something to do with either of the following lines - both of which I have been fiddling around with to no avail.
echo "['".$date."', ".$speed."],";
data.addColumn('string', 'Date');
data.addColumn('number', 'Speed');
Thank you very much. All suggestions and ideas are very welcome. As is probably evident I am very new to Javascript so likely to be making some stupid mistakes.
A couple of things I would say: As you appear to wish to use a date within the dataTable perhaps setting that as a date type column would be better and casting the value from the db query as a date using new Date(str). I'd also suggest that you use json_encode once you have run the db query to create a JSON object rather than manually building a string as you do above - one downside to that approach is the trailing comma which might cause issues.
I rattle together a working demo using bogus data from my db to emulate what you were trying to do here. The SQL query uses aliases to take arbitrary data and name it as you do so the Javascript remains fairly much the same.
With the JSON data it is easy to iterate through the Object using Object.keys( json ).forEach() type structure ( I apologise if this is new to you )
<?php
#add a db connection
chdir('../../dbo');
require 'db-conn-details.php';
require 'mysqli-conn.php';
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//www.gstatic.com/charts/loader.js'></script>
<script></script>
<title>Google charts.....</title>
<style>
#chart_div{
width:800px;height:600px
}
</style>
</head>
<body>
<div id='chart_div'></div>
<script>
<?php
$sql = 'SELECT `speed`, `date_completed` FROM `rides_done` WHERE ( `id_users` = $_SESSION[id] )';
$sql = 'select `dr` as `speed`, date(`lasteditdate`) as `date_completed` from `testtable` limit 20'; # example sql...
$result = $link->query( $sql );
$json = json_encode( $result->fetch_all( MYSQLI_ASSOC ) );
printf('const json=%s;', $json );
?>
google.charts.load('current', { packages: ['corechart'] } );
google.charts.setOnLoadCallback( drawBasic );
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Speed');
Object.keys( json ).forEach( key=>{
let obj=json[ key ];
data.addRow( [ new Date( obj.date_completed ), parseFloat( obj.speed ) ] );
})
var options = {
hAxis: {
title: 'Ride date'
},
vAxis: {
title: 'Average speed'
}
};
var chart = new google.visualization.LineChart( document.getElementById('chart_div') );
chart.draw( data, options );
}
</script>
</body>
</html>
The above yielded a chart like this:

Google Charts - Put data by PHP echo

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) ?>);

How do I create a C3 Chart Line Graph from JSON data?

I need help for a school project. I have been able to pull data from a mySQL database into an array and encoded into JSON, which displays fine. Now, I need help with passing the JSON data to C3 to produce a chart (if possible on the same page).
What I've done so far:
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
echo json_encode( $data );
You need to create two separate array, one for your data and one for dates that you want to show on x-axis and then pass that array to java script.
here is full working example
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$valuesArray = array();
$datesArray = array();
$valuesArray[] = 'Oil';
$datesArray[] = 'x';
while ($row = $result->fetch_assoc()) {
$datesArray[] = $row['production_date'];
$valuesArray[] = $row['oil'];
}
?>
<html>
<head>
<title>C3 Liner example</title>
<link href="c3_scr/c3.css" rel="stylesheet" type="text/css" />
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="c3_scr/c3.js"></script><!-- load jquery -->
</head>
<body>
<div id="chart"></div>
<script>
var xAxisArr = <?php echo json_encode($datesArray); ?>;
var dataArr = <?php echo json_encode($valuesArray, JSON_NUMERIC_CHECK); ?>;
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'x',
columns: [
xAxisArr,
dataArr
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d'
}
}
}
});
</script>
</body>
</html>

SELECT Count from mysql to Google Geo Chart

I've been trying to retrieve data from mysql database using SELECT Count, as I got a list of countries which I want to count how many times each country is displayed in the column SovereignState, to a Google Geo Chart and by browsing around, I believe that json_encode should do the trick.
However, I have no idea how to get make a json_encode from my php code and then put it in the DataTable of the chart.
This is the php code:
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASSWORD','');
define('DB_HOST', '');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) ;
if ($conn->connect_error) {
die ('Could not connect: ' . $conn->connect_error);
}
$sql = "SELECT SovereignState, COUNT(*) FROM Data_2 GROUP BY SovereignState";
echo $sql;
//$result = $conn->query($sql);
$result = $conn->multi_query($sql);
if(!$result) {
echo "Could not successdully run query ($sql) from DB: " . mysql_error(); exit;
}
echo "<pre>";
do {
if ($result = $conn->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s - %s\n", $row[0], $row[1]);
}
$result->free();
}
} while ($conn->more_results());
echo "</pre>";
$conn->close();
And this is the html code of the google geochart:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["geochart"]});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Number'],
]);
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
</script>
You can use json_encode() from your PHP code and use Ajax in order to get the JSON into your JS code.
Also, (not recommended) you can just call a PHP function from your JS code with <?php myFunction();?>, that function should return an echo json_encode().

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