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

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

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:

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

how can i transform my josn_encode data in array into google bar chart?

This is my json_encoded data
$encoded_data = json_encode($data);
echo $encoded_data;
[{"cols":"2017-09-02 11:01:55","rows":"1186.55"},{"cols":"2017-09-03 11:31:35","rows":"1311.45"},{"cols":"2017-09-06 15:22:38","rows":"90000.00"},{"cols":"2017-09-06 16:39:16","rows":"90000.00"},{"cols":"2017-09-06 16:40:09","rows":"630.00"},{"cols":"2017-09-06 17:25:26","rows":"1311.45"},{"cols":"2017-09-06 17:54:50","rows":"1311.45"},{"cols":"2017-09-07 09:28:57","rows":"1311.45"},{"cols":"2017-09-07 10:20:16","rows":"1575.00"},{"cols":"2017-09-07 10:22:28","rows":"1311.45"},{"cols":"2017-09-07 10:27:52","rows":"1311.45"},{"cols":"2017-09-07 10:34:00","rows":"1311.45"},{"cols":"2017-09-07 10:39:46","rows":"91575.00"},{"cols":"2017-09-07 10:40:48","rows":"91311.45"},{"cols":"2017-09-07 10:47:34","rows":"1575.00"},{"cols":"2017-09-07 10:50:53","rows":"1575.00"},{"cols":"2017-09-07 10:51:18","rows":"1575.00"}]
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var jsonData = <?php echo $encoded_data; ?>
var data = new google.visualization.DataTable(jsonData);
// Set chart options
var options = {'title':'sales chart',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
It gives me an error the table has no columns.
the json is not in the correct format to create the data table directly,
see the structure of the JavaScript literal object described here...
if you don't want to change the format, then it can be transformed using javascript
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var jsonData = [{"cols":"2017-09-02 11:01:55","rows":"1186.55"},{"cols":"2017-09-03 11:31:35","rows":"1311.45"},{"cols":"2017-09-06 15:22:38","rows":"90000.00"},{"cols":"2017-09-06 16:39:16","rows":"90000.00"},{"cols":"2017-09-06 16:40:09","rows":"630.00"},{"cols":"2017-09-06 17:25:26","rows":"1311.45"},{"cols":"2017-09-06 17:54:50","rows":"1311.45"},{"cols":"2017-09-07 09:28:57","rows":"1311.45"},{"cols":"2017-09-07 10:20:16","rows":"1575.00"},{"cols":"2017-09-07 10:22:28","rows":"1311.45"},{"cols":"2017-09-07 10:27:52","rows":"1311.45"},{"cols":"2017-09-07 10:34:00","rows":"1311.45"},{"cols":"2017-09-07 10:39:46","rows":"91575.00"},{"cols":"2017-09-07 10:40:48","rows":"91311.45"},{"cols":"2017-09-07 10:47:34","rows":"1575.00"},{"cols":"2017-09-07 10:50:53","rows":"1575.00"},{"cols":"2017-09-07 10:51:18","rows":"1575.00"}];
var data = new google.visualization.DataTable();
data.addColumn('string', 'x');
data.addColumn('number', 'y');
jsonData.forEach(function (row) {
data.addRow([
row.cols,
parseFloat(row.rows)
]);
});
var options = {
title: 'sales chart',
width: 400,
height: 300,
chartArea: {
left: 140
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Bar Chart from Mysql Database

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.

Categories