Google Charts Pie chart displaying Other 100% - php

<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([
['Task', 'Hours per Day'],
<?php
$query = "SELECT name, score FROM `Users` order by score desc limit 5";
$result = mysqli_query($conn, $query);
if ($result->num_rows > 0) {
while($row = mysqli_fetch_array($result))
{
echo "['".$row['name']."', '".$row['score']."'],";
}
}
?>
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
What is wrong with my code? i have read that my values are stored as string so that the chart is showing 100% other.
How do i make it work? i tried with (int)$var PHP function, but that does not make it work yet..
while($row = mysqli_fetch_array($result))
{
$score = $row['score'];
$int = (int)$score;
echo "['".$row['name']."', '".$row['score']."'],";
}
}

Do not generate json by yourself. Use json_encode always:
<?php
$query = "SELECT name, score FROM `Users` order by score desc limit 5";
$result = mysqli_query($conn, $query);
$chartData = [
['Task', 'Hours per Day'],
];
if ($result->num_rows > 0) {
while($row = mysqli_fetch_array($result))
{
$chartData[] = [$row['name'], $row['score']];
}
}?>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo json_encode($chartData)?>);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>

Related

Using arrays to feed Google datetime chart plot

I have meteorological data that I am retrieving through MySQL and can see it through phpMyAdmin. I am trying to plot stuff but I get no data in the plot.
My code is
<?php
// connect to database
$conn = mysqli_connect('localhost', 'root', 'station', 'meteobridge');
// check connection
if(!$conn){
echo 'Connection error: ' . mysqli_connect_error();
}
// write query for data
$sql = 'SELECT ID,TempInCur,TempOutCur FROM mystation';
$dateFormat = 'SELECT DateTime FROM mystation';
// make query & get result
$result = mysqli_query($conn, $sql);
$dtresult = mysqli_query($conn, $dateFormat);
// fetch the resulting rows as an array
$dailyMeasurements = mysqli_fetch_all($result, MYSQLI_ASSOC);
$dtArray = mysqli_fetch_all($dtresult, MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html>
<?php include('templates/header.php'); ?>
<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 = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'TempIn');
data.addColumn('number', 'TempOut');
data.addRows([
[ <?php $dtArray[0]['DateTime'] ?>, <?php echo $dailyMeasurements[0]['TempInCur'] ?>,<?php echo $dailyMeasurements[0]['TempOutCur'] ?>],
[ <?php $dtArray[1]['DateTime'] ?>,<?php echo $dailyMeasurements[1]['TempInCur'] ?>,<?php echo $dailyMeasurements[1]['TempOutCur'] ?>],
[ <?php $dtArray[2]['DateTime'] ?>,<?php echo $dailyMeasurements[2]['TempInCur'] ?>,<?php echo $dailyMeasurements[2]['TempOutCur'] ?>]
]);
var options = {
title: 'Temperaturas',
//curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
<?php include('templates/footer.php'); ?>
</html>
The values for $dailyMeasurements[*]['TempInCur'] are 27.1, and 28.7 for $dailyMeasurements[*]['TempOutCur']. And the values of $dtArray[0]['DateTime'] are 2020-12-27 16:58:26, 2020-12-27 17:03:28, 2020-12-27 17:08:31.
The reason I am adding data with only the first few indexes of my arrays is because when I tried using the whole array (a long time ago), I would have more errors without understanding the problems. I tried making a simple example where I could try to figure out as a beginner what's going on and what is wrong. That made it possible to even get the following image of the resulting dataless plot.
If you have a way to feed the arrays directly to Google charts then that's even better! My intention was to figure out that after I am able to produce a plot.
I'm not sure but you get an associative array.
You should convert this array to an object
const objDatas = JSON.parse($dtArray);
then
GoogleCharts.load("current", { packages: ['corechart'], callback: drawChart });
function drawChart() {
//use objDatas.yourProperty
It worked for me
first, the sql. it looks like all columns are coming from the same table,
so why not include them all in the same query...?
from...
$sql = 'SELECT ID,TempInCur,TempOutCur FROM mystation';
$dateFormat = 'SELECT DateTime FROM mystation';
to...
$sql = 'SELECT DateTime,TempInCur,TempOutCur FROM mystation';
next, build your array in php...
// make query & get result
$result = mysqli_query($conn, $sql);
$rows = array();
while($row = mysqli_fetch_array($result)){
$rows[] = array($row['DateTime'], $row['TempInCur'], $row['TempOutCur']);
}
then write it to the page in the addRows method...
data.addRows(<?php echo json_encode($rows); ?>);
see following snippet...
<?php
// connect to database
$conn = mysqli_connect('localhost', 'root', 'station', 'meteobridge');
// check connection
if(!$conn){
echo 'Connection error: ' . mysqli_connect_error();
}
// write query for data
$sql = 'SELECT DateTime,TempInCur,TempOutCur FROM mystation';
// make query & get result
$result = mysqli_query($conn, $sql);
$rows = array();
while($row = mysqli_fetch_array($result)){
$rows[] = array($row['DateTime'], $row['TempInCur'], $row['TempOutCur']);
}
?>
<!DOCTYPE html>
<html>
<?php include('templates/header.php'); ?>
<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 = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'TempIn');
data.addColumn('number', 'TempOut');
data.addRows(<?php echo json_encode($rows); ?>);
var options = {
title: 'Temperaturas',
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: 900px; height: 500px"></div>
</body>
<?php include('templates/footer.php'); ?>
</html>

Connecting Google`s Gantt Chart to MySql Database

I am attempting to use google`s gantt chart for a website, by passing values from a mysql database. However I am only seeing a blank page.
The chart I wish to use is:
gantt chart
The current gantt code I have used is:
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
$connect = mysqli_connect("localhost", "root", "", "registration");
?>
<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.load('current', {'packages':['gantt']});
google.charts.setOnLoadCallback(drawGanttChart);
function drawGanttChart() {
var data = new google.visualization.arrayToDataTable();
data.addColumn('string', 'taskid');
data.addColumn('string', 'taskname');
data.addColumn('string', 'membername');
data.addColumn('string', 'sdate');
data.addColumn('string', 'edate');
data.addColumn('string', 'duration');
data.addColumn('number', 'percentage');
data.addColumn('string', 'dependency');
data.addRows([
['taskid', 'taskname', 'membername', 'sdate', 'edate','duration', 'percentage', 'dependency'],
<?php
$query10 = "select * from gantt";
$result10 = mysqli_query($connect, $query10);
while($row = mysqli_fetch_array($result10))
{
echo "['".$row["taskid"]."', '".$row["taskname"]."', '".$row["membername"]."', ".$row["sdate"].", ".$row["edate"].", ".$row["duration"].", ".$row["percentage"].", ".$row["dependency"]."],";
}
?>
]);
var options = {
height: 400,
gantt: {
trackHeight: 30
}
};
var chart = new google.visualization.Gantt(document.getElementById('Gantt_chart_div'));
chart.draw(data, options);
}
</script>
<body>
<div id="Gantt_chart_div" style="border: 1px solid #ccc"></div>
</body>
</html>
data
Please note, I managed to get the pie chart to work using different data, but I am unable to get the syntax correct for gantt, the pie chart (working) code is as follows:
function drawSarahChart() {
var data = google.visualization.arrayToDataTable([
['domain', 'NUMBER'],
<?php
//$query="SELECT projects.id, count(*) as NUMBER FROM projects INNER JOIN users ON projects.members = users.email";
$query = "SELECT projects.domain, COUNT(projects.domain) AS NUMBER FROM projects INNER JOIN users ON projects.members = users.email WHERE users.company = 'vit' GROUP BY projects.domain ";
$result5 = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result5))
{
echo "['".$row["domain"]."', ".$row["NUMBER"]."],";
}
?>
]);
var options = {title:'Classification on the basis of domain',
is3D: true,
width:400,
height:400};
var chart = new google.visualization.PieChart(document.getElementById('Sarah_chart_div'));
chart.draw(data, options);
}

Pie chart using mysql and php

I am using this code from internet. But in this the data is static but i want to draw a chart with my database entries. can u tell me how to add mysql data in this code
<div class="hellcontainer">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<dcript type="text/javascript">
google.load("visualization","1",{packages:["corechar"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data=google.visualization.arrayToDataTable([
['Languages','speakers(in millions)'],
['Assamese,13'],['Punjabi',45]]);
var options = {
title:''
};
var chart=new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
Here is a rough code to do this in php, you can change it according to your need:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$db = "dbname";
$conn = mysqli_connect($servername, $username, $password, $db); // update your connection params
$query = "SELECT state, lang_number FROM state"; //update your query as needed
$results = mysqli_query($conn, $query);
$pieData = array();
while ($row = mysqli_fetch_array($results)) {
$acc_type = $row ['state'];
$acc_num = $row ['lang_number'];
$pieData[] = array($row['state'], $row['lang_number']);
}
?>
<div class="hellcontainer">
<div id="chart_div"></div>
</div>
<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 = new google.visualization.DataTable();
data.addColumn('string', 'State');
data.addColumn('number', 'speakers(in millions)');
data.addRows(<?php echo json_encode($pieData, JSON_NUMERIC_CHECK); ?>);
var options = {'title':'Language spoken',
'width':400,
'height':300};
var chart=new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
Hope that helps.
<div class="hellcontainer">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<dcript type="text/javascript">
google.load("visualization","1",{packages:["corechar"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data=google.visualization.arrayToDataTable([
['Languages','speakers(in millions)'],
['Assamese,13'],['Punjabi',45]]);
var options = {
title:''
};
var chart=new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>

Draw graph with sql variables

I used Google graph to draw a graph by below code, but the problem is that my data is on a sql table, how can I put my table variables into this graph?
<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([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance'
};
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>
<?php
$result = mysql_query("SELECT year,sales,expenses from tablename");
$value=array();
while($r = mysql_fetch_assoc($result)) {
$year=$r['year'];
$sales=$r['sales'];
$expenses=$r['expenses'];
$val="[".$year.",".$sales.",".$expenses."]";
array_push($value,$val );
}
$final_value = implode(",", $value);
?>
put this $final_value into google chart
function drawChart() {
var data = google.visualization.arrayToDataTable([
<?php echo $final_value?>
]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Retrieve your data From tables by querying database and convert it to JSON string. Then pass your json string to your variable
var data=/*your json string*/
$db = new mysqli('localhost', 'user', 'pass', 'demo');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = "SELECT attempt, login FROM result";
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
echo "var data = google.visualization.arrayToDataTable([['Attempt', 'Login']";
while($row = $result->fetch_assoc()){
echo ",['".$row['attempt'] ."','".$row['attempt']."']";
}
echo "]);";
$result->free();
$db->close();

Unable to run my HTML code in google chrome

I am trying to use Google charts and integrate in my android app. Before that I tried to check my html code in Google chrome. In that code I have tried to integrate to get the data from the MYSQL.
My code as follows
<?php
$server = "localhost";
$user="root";
$password="";
$database = "mobiledb";
$connection = mysql_connect($server,$user,$password)
or
trigger_error(mysql_error(),E_USER_ERROR);
$db = mysql_select_db($database,$connection);
$sth = mysql_query("SELECT * FROM `table` WHERE `x-axis` AND `y-axis` LIMIT 0, 30 ");
while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($x-axis);
$arr1=array_values($y-axis);
}
for($i=0;$i<count($arr1);$i++)
{
$chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
}
echo "<pre>";
$data=json_encode($chart_array);
?>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<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() {
$(function () {
var data = new google.visualization.DataTable();
data.addColumn("string", "x-axis");
data.addColumn("number", "y-axis");
data.addRows(<?php $data ?>);
});
var options = {
title: 'Details',
is3D: 'true',
width: 800,
height: 600
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
But I am unable to see the graph. And I was getting the following error "; $data=json_encode($chart_array); ?> And when I inspect the page I was found the following error *Uncaught SyntaxError: Unexpected token < * Please help me in solving this.
check your query
$sth = mysql_query("SELECT `x-axis`,`y-axis` FROM `table` LIMIT 0, 30 ");
if you want column x-axis and y-axis then use this
then correct this
data.addRows(<?php echo $data ?>);
You may need to correct this line probably
data.addRows(<?php $data ?>); //incorrect
data.addRows(<?php echo($data); ?>); //you forgot to echo it
There are so many problem with your PHP code
//what is this?
$sth = mysql_query("SELECT * FROM `table` WHERE `x-axis` AND `y-axis` LIMIT 0, 30 ");
//probably you want this?
$sth = mysql_query("SELECT `x-axis`, `y-axis` FROM `table` LIMIT 0, 30 ");
//this is wrong
while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($x-axis);
$arr1=array_values($y-axis);
}
//try this
while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($r['x-axis']);
$arr1=array_values($r['y-axis']);
}
//where is $chart_array defined? It should be like this
$chart_array = array();
for($i=0;$i<count($arr1);$i++)
{
$chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
}

Categories