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);
?>
Related
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:
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);
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
i am using google chart and displaying column chart. That's working fine. my code is
google.charts.load('current', {'packages':['columnchart']});
google.charts.setOnLoadCallback(drawChartTwo);
function drawChartTwo() {
var data = google.visualization.arrayToDataTable([
['Type', 'Total'],
<?php
foreach($val as $data){
echo "['".$data['type']."', ".$data['total']."],";
}
?>
]);
var options = {
hAxis: {
title: 'Type'
},
vAxis: {
title: 'Total'
},
'width':830,
'height':300,
'title': 'Outage Analysis',
'is3D': true,
//set color base on $data['unit']
};
var chart1 = new google.visualization.ColumnChart(document.getElementById('chart_bar'));
chart1.draw(data, options);
}
now, in my database i have another column $data['unit'] and it have four different category and i want to display different colors of column for different category. so, my question is how can i use my php column $data['unit'] to set colors on column in column chart?
use a 'style' column role
you can populate the column with html color strings...
e.g. --> #f44336
var data = google.visualization.arrayToDataTable([
['Type', 'Total', {role: 'style'}],
<?php
foreach($val as $data){
echo "['".$data['type']."', ".$data['total'].", '".$data['color']."'],";
}
?>
]);
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var data = new google.visualization.arrayToDataTable([
['Type', 'Total', {role: 'style'}],
['A', 10, '#f44336'],
['B', 14, '#e91e63'],
['C', 16, '#9c27b0'],
['D', 22, '#673ab7'],
['E', 28, '#3f51b5'],
['F', 14, '#2196f3']
]);
var options = {
height: 300,
legend: {
position: 'none'
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(container);
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
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.