I'm trying to draw a Pie Chart with my database. I used Google Pie Chart , PHP and MySql.
I run the code doesn't show any errors but I don't see pie chart showing up.
Can please someone tell me where to modify to make it work?
Thanks.
<?php
/* Your Database Name */
$dbname = 'chart';
$username = 'root';
$password = '';
try {
/* Establish the database connection */
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/* select all the weekly tasks from the table googlechart */
$result = $conn->query('SELECT Nature, concat((count( * ) *100 / (SELECT count( * ) FROM `tfichiers`)) , "%") AS percent FROM `tfichiers` GROUP BY Nature ');
$rows = array();
$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 Slice title
*/
array('label' => 'Nature', 'type' => 'string'),
array('label' => 'percent', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
// the following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['Nature']);
// Values of each slice
$temp[] = array('v' => (int) $r['percent']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
//echo $jsonTable;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
<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: 'Demande par Nature',
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"></div>
</body>
</html>
Related
I need help with drawing chart that is auto updating. I currently have two php files, one which gets data from MySQL database and turns it into JSON get_json.php, and the other that turns gotten data into chart, linechart.php.
Chart appears, but there is nothing on it, and both axis go from 0 to 1, and I need x axis to be TimesStamp column from database.
Here are codes:
get_json.php
<?php
$con = mysqli_connect('localhost', 'u644759843_miki', 'plantaze2020!') or die('Error connecting to server');
mysqli_select_db('u644759843_plantazeDB', $con);
// write your SQL query here (you may use parameters from $_GET or $_POST if you need them)
$query = mysqli_query('SELECT `FlowRate`, `ProductPurity`, `TimesStamp` FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 10');
$table = array();
$table['cols'] = array(
/* define your DataTable columns here
* each column gets its own array
* syntax of the arrays is:
* label => column label
* type => data type of column (string, number, date, datetime, boolean)
*/
// I assumed your first column is a "string" type
// and your second column is a "number" type
// but you can change them if they are not
array('label' => 'FlowRate', 'type' => 'number'),
array('label' => 'ProductPurity', 'type' => 'number'),
array('label' => 'TimesStamp', 'type' => 'number')
);
$rows = array();
while($r = mysqli_fetch_assoc($query)) {
$temp = array();
// each column needs to have data inserted via the $temp array
$temp[] = array('v' => (int) $r['ProductPurity']);
$temp[] = array('v' => (int) $r['FlowRate']);
$temp[] = array('v' => (int) $r['TimesStamp']); // typecast all numbers to the appropriate type (int or float) as needed - otherwise they are input as strings
// insert the temp array into $rows
$rows[] = array('c' => $temp);
}
// populate the table with rows of data
$table['rows'] = $rows;
// encode the table as JSON
$jsonTable = json_encode($table);
// set up header; first two prevent IE from caching queries
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
// return the JSON data
echo $jsonTable;
?>
linechart.php
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
// 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() {
//AJAX Call is compulsory !
var jsonData = $.ajax({
url: "/nitrogengenerator/get_json.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'Nitrogen Generator',
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>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// First load the chart once
drawChart();
// Set interval to call the drawChart again
setInterval(drawChart, 5000);
});
</script>
<!-- Kraj koda za grafik -->
</head>
<body>
<div id="chart_div"> </div>
</body>
</html>
I am pulling data from a mysql database in a PHP script and using google charts to display the data graphically. It worked fine when using a pie or bar chart with only 2 variables to deal with. Now I want to use a ComboChart. I have 4 fields in a table: Name, Date, Quanity, Cost. I want to have a ComboChart where along the x-axis is the Date, a bar graph will represent the Quantity, and a line graph will represent the Cost.
Here is the code I have so far. How can I go about doing this? In the drawChart() function there's no explicit order to what is on the x or y axis so how do I know which of my data is being displayed where? Does that depend on what order you select the data in during the mysqli_query?
// host, username, password and dbname are already declared
$conn = mysqli_connect($host, $username, $password);
if ($conn->connect_error) {
die("Could not connect: " . mysql_error()) . "<br>";
}
mysqli_select_db($conn, $dbname);
$qresult = mysqli_query($conn, "SELECT * FROM Scrap");
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Date', 'type' => 'string'),
array('label' => 'Quantity', 'type' => 'number'),
array('label' => 'Cost', 'type' => 'number')
);
$rows = array();
while ($r = $qresult->fetch_assoc()) {
$temp = array();
$temp[] = array('v' => (string) $r['Date']);
// Values of each slice
$temp[] = array('v' => (int) $r['Quantity']);
$temp[] = array('v' => (float) $r['Cost']);
$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: 'YTD Controllable Scrap Costs',
seriesType:'bars',
series:{2: {type: 'line'}}
// 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.ComboChart(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>
So I tested around and I found out that the first column is the x-axis and the 2nd, 3rd, 4th, etc go on the y-axis. The reason the bar AND line graph weren't showing up was because in my drawChart() function, where it says: series:{2: {type: 'line'}}, the number 2 refers to the 3rd field for the y-axis since it is zero-indexed. I didn't have a 3rd field for the y-axis, so I switched it to series:{1: {type: 'line'}} and now I get a bar graph and a line graph.
I'm trying to get Google Charts to display a graph of what I have in my MySQL database. Unfortunately, it's not displaying anything. I know there has to be some sort of small error that I'm missing.
<?php
mysql_connect("Localhpst", "Username", "password");
mysql_select_db("DBName") or die(mysql_error());
$sth=mysql_query("SELECT *
FROM Graph")
or die(mysql_error());
$rows = array();
$flag = true;
$table = array();
$table['cols'] = array(
array('label' => 'people', 'type' => 'string'),
array('label' => 'total', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
$temp[] = array('v' => (string) $r['people']);
$temp[] = array('v' => (int) $r['total']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<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">
// 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: ' Something ',
is3D: 'true',
width: 800,
height: 600
};
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"></div>
</body>
</html>
What is missing that would result in this displaying nothing on the screen. The only thing it displays is the "Something" from the title. I know there is data in the database, so that's not the issue. I'm also fairly certain it's not a connection issue, so I'm stumped.
Thanks for all the inputs from Stackoverflow. I am able to place the 2 google chart in one page, but the 2nd chart is showing below 1st chart. But i need both charts in parallel to each other.
Like:
1st chart from Left it should be 100th position, top =200 and 2nd chart should be 300th position, top=200. How can i achieve that. I used chartArea:{left:20,top:0,width:"50%",height:"75%"}, but i am not getting
<?php
$con=mysql_connect("","root","") or die("Failed to connect with database!!!!");
mysql_select_db("Loan_Bids", $con);
$sth = mysql_query("SELECT A.Bid_Size, B.Rating from bids_data A, loan_data B Where A.LoanID = B.LoanID");
$rows = array();
$rows1 = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
array('label' => 'Bid_Size', 'type' => 'number'),
array('label' => 'Rating', 'type' => 'number')
);
$table1 = array();
$table1['cols'] = array(
array('label' => 'Bid_Size', 'type' => 'number'),
array('label' => 'Rating', 'type' => 'number')
);
$rows = array();
$rows1 = array();
while($r = mysql_fetch_assoc($sth)) {
$Ratingval = $r['Rating'];
if ($Ratingval == 1 )
{
$temp = array();
// the following line will be used to slice the Pie chart
$temp[] = array('v' => (int) $r['Bid_Size']);
// Values of each slice
$temp[] = array('v' => (int) $r['Rating']);
$rows[] = array('c' => $temp);
}
if ($Ratingval == 2 )
{
$temp1 = array();
// the following line will be used to slice the Pie chart
$temp1[] = array('v' => (int) $r['Bid_Size']);
// Values of each slice
$temp1[] = array('v' => (int) $r['Rating']);
$rows1[] = array('c' => $temp1);
}
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
$table1['rows'] = $rows1;
$jsonTable1 = json_encode($table1);
echo $jsonTable1;
?>
<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">
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(<?php echo $jsonTable?>);
var options = {
title: 'Rating1',
is3D: 'true',
color:'red',
hAxis: {title: 'Interest Rate'},
vAxis: {title: 'Bid Size'},
width:200,height:200
};
var data1 = new google.visualization.DataTable(<?php echo $jsonTable1?>);
var options1 = {
title: 'Rating2',
is3D: 'true',
hAxis: {title: 'Interest Rate'},
vAxis: {title: 'Bid Size'},
width:200,height:200
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
var chart1 = new google.visualization.ScatterChart(document.getElementById('chart_div1'));
chart1.draw(data1, options1);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
<div id="chart_div1"></div>
</body>
</html>
You need to use CSS to position the container divs on the page, not the chartArea options. Something like this should work:
#chart_div, #chart_div1 {
float: left;
width: 50%;
}
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