Google Bar Chart from Mysql Database - php

I have a mysql db with 3 fields region(vachar), new_customers(int) and old_customers(int).
I am trying to create a bar chart with google charts and php but it doesn't work. I think i am doing sth wrong on echo.
Here is my code:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawMaterial);
function drawMaterial() {
var data = google.visualization.arrayToDataTable([
['Region', 'New Customers', 'Old Customers'],
<?php
$query = "SELECT sum(new_customers) AS new, sum(old_customers) AS old, region FROM daily GROUP BY region";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['region']."',";
echo "['".$row['new']."',";
echo "['".$row['old']."',";
}
?>
]);
var options = {
title: 'Country wise new and returned visitors',
bars: 'horizontal'
};
var material = new google.charts.Bar(document.getElementById('barchart'));
material.draw(data, options);
}
</script>

The problem you are having is that the chart is not taking the three parameters in the data variable.
At the moment you have it like: ['Region', 'New Customers', 'Old Customers'],.
Change it to: ['Region', 'New Customers'],.
In the while loop, PHP is not recognising any column with the name $row['new'] or $row['old']. Instead use indexes and change your echo to:
echo "['".$row[2]." [".$row[0]."]', ".$row[1]."],";
I would also recommend you to have the sql query outside the function and have only the iteration through the sql results (the while loop with the echo).
Also, you were not loading the charts properly. You forgot to add the word 'charts':
google.charts.load('visualization', '1', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawMaterial);
This is the final solution:
<?php
include("YOUR PHP CONNECT FILE");
$query = "SELECT sum(new_customers) AS new, sum(old_customers) AS old, region FROM daily GROUP BY region";
$exec = mysqli_query($YOURCONNECTIONVARIABLE ,$query);
?>
<!DOCTYPE html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('visualization', '1', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawMaterial);
function drawMaterial() {
var data = google.visualization.arrayToDataTable([
['Region', 'New Customers'],
<?php
while($row = mysqli_fetch_array($exec)){
echo "['".$row[2]." [".$row[0]."]', ".$row[1]."],";
}
?>
]);
var options = {
title: 'Country wise new and returned visitors',
bars: 'horizontal'
};
var material = new google.charts.Bar(document.getElementById('barchart'));
material.draw(data, options);
}
</script>
</head>
<body>
<div id="barchart" style="width: 100%; height: 40em;"></div>
</body>
</html>
Let me know if you have any questions.

Related

Displaying specific users input in Google Graphs with mySQL

Im new to php and mysql and we have a project where we want to display a specific users input in a google chart.
In the mysql table I have 2 different values (admin, test) under a row called user_name.
When the code is as I linked, the chart shows all the inputs, no matter if they are from the user "test" or the user "admin" and works as it should.
But when I change
$query="
select *
from temp
"
to
$query=
"select *
from temp
where user_name=test
"
the chart stops working.
Any help how to solve this is much appreciated!
<!-- The scripts for the graph -->
<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([
['Day', 'Outdoor', 'Indoor'],
//PHP Code
<?php
$query="select * from temp";
$res=mysqli_query($mysqli,$query);
while($data=mysqli_fetch_array($res)){
$day=$data['created_at'];
$outdoor=$data['outdoor'];
$indoor=$data['indoor'];
?>
['<?php echo $day;?>',<?php echo $outdoor;?>,
<?php echo $indoor;?>],
<?php
}
?>
]);
var options = {
title: 'Temperature',
subtitle: 'Temperature outside and inside',
curveType: 'none',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart
(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
mysql table:

Changing the legend/labels in Google Chart

I am pulling data from a database via mysqli to create a Google pie Chart. The data is from one column (a1), but each entry is different (eg, a, b, c) and I am listing the percentage of responses for each entry/answer.
So for instance,
a = 20%
b = 30%
Each entry corresponds to a different social media type, which I need to show but is not shown in the database itself. Is there a way to change the legend of the chart so that instead of listing A, B, C it would replace that with a custom label? (Eg, instead of showing 'A' show 'Facebook').
my column
my current chart
I have tried using title under var data, label under options, legend under options. I feel like I'm missing something
<?php
$connect = mysqli_connect("localhost", "root", "root", "survey");
$query = "SELECT a1, count(*) as number FROM rtp2k GROUP BY a1";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Sad me is Sad </title>
<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([
['social', 'number'],
<?php
while($row = mysqli_fetch_array($result))
{
echo "['".$row["a1"]."', ".$row["number"]."],";
}
?>
]);
var options = {
title: 'Which social networks do you use most often?',
//is3D:true,
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<br /><br />
<div style="width:900px;">
<h3 align="center">Make Simple Pie Chart by Google Chart API with PHP Mysql</h3>
<br />
<div id="piechart" style="width: 900px; height: 500px;">
</div>
</div>
</body>
</html>
Right now my legend lists the type by what is in the database, (eg, a, b, c) I would like to replace the letters with my own label/title (eg, instead of 'a', I would like it to say 'Facebook'.
Edited for consistency.
we can use a DataView with a calculated column,
to convert the values the network names.
first, create an object to map the values to the names.
var socialNetworks = {
a: 'Facebook',
b: 'Instagram',
c: 'LinkedIn'
};
then we create a DataView from the DataTable.
var view = new google.visualization.DataView(data);
then use method setColumns to add a calculated column for the conversion.
we use the column index of the number, since it won't be changing.
view.setColumns([{
calc: function (dt, row) {
return socialNetworks[data.getValue(row, 0)];
},
label: 'social',
type: 'string'
}, 1]);
then use the DataView to draw the chart.
chart.draw(view, options);
full snippet...
var data = google.visualization.arrayToDataTable([
['social', 'number'],
<?php
while($row = mysqli_fetch_array($result))
{
echo "['".$row["a1"]."', ".$row["number"]."],";
}
?>
]);
var options = {
title: 'Which social networks do you use most often?',
//is3D:true,
pieHole: 0.4,
};
var socialNetworks = {
a: 'Facebook',
b: 'Instagram',
c: 'LinkedIn'
};
var view = new google.visualization.DataView(data);
view.setColumns([{
calc: function (dt, row) {
return socialNetworks[data.getValue(row, 0)];
},
label: 'social',
type: 'string'
}, 1]);
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(view, options);

how to set post variable in the sql query to get difference between two dates

I set two variable in date format then i put it in the sql query to find data between two dates and to show them as column chart. But its not working. without script code it shows proper data but when i include script for column it doesn't display any output any suggestion?
Here is the code:
<?php
$user='root';
$pass='';
$db='mypro_bms';
$conn = mysqli_connect('localhost',$user,$pass,$db);
$count=0;
if(isset($_POST['search'])){
$txtStartDate = date('Y-m-d',strtotime($_POST['txtStartDate']));;
$txtEndDate = date('Y-m-d',strtotime($_POST['txtEndDate']));;
$q=mysqli_query($conn,"SELECT blood_group, SUM(blood_bag) as sum FROM donate where date(donation_date)between'$txtStartDate' and '$txtEndDate' group by blood_group");
$count=mysqli_num_rows($q);
}
?>
<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([
['sum','blood_group'],
<?php
if ($count=="0")
{
echo "No data"; }
else
{
while ($row=$q->fetch_assoc()) {
echo"['".$row['blood_group']."',".$row['sum']."],";
}
}
?>
]);
var options = {
title: 'Blood volume',
is3D: true,
};
var chart = new google.visualization.ColumnChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>

Create a Google Charts from PHP with Wordpress and MySQL Database

I'm trying to insert google charts in Wordpress website from MySQL database using php.
Below my data source:
PHP-MySQL-Google Chart Example:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo $chartDataInJson; ?>);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
I want to fill the array $chartDataInJson like below:
<?php
$chartData = array(
array('created_date', 'AAA', 'BBB', 'CCC'),
array('2018-09-07', 9, 7, 4),
array('2018-09-08', 10, 6, 12),
array('2018-09-09', 11, 5, 3)
);
$chartDataInJson = json_encode($chartData);
?>
Please how to dynamically load these values from the database with php. I tried this:
<?php
global $wpdb;
$result = "SELECT * FROM stat GROUP BY created_date";
$chartData = array();
foreach ($result as $row) {
//code
}
$chartDataInJson = json_encode($chartData);
?>

PHP how to generate charts from mysql data (google charts)

I'm making a report using GOOGLE Chart. I tried a lot of option but It still not working. How do I generate the report with a proper result?
My query with a result
Database with Query
My current code `
<?php
require '../include/db-conn.php';
session_start();
$query = "SELECT YEAR(ddate), treatment, count(*) AS count FROM
patient_records GROUP BY YEAR(ddate), treatment";
$aresult = $mysqli->query($query);
?>
<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([
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo " ['Year', '".$row["treatment"]."',],
['".$row["YEAR(ddate)"]."', ".$row['count']."],";
}
?>
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(data, options);
}
</script>
The result with current code

Categories