How to plot data from msyql with google chart in wordpress - mysql

I have been struggling with adding
google chart with my own mysql data to my wordpress page.
When I use this code in a simple html form. It works just fine:
http://fiber.web.tuke.sk/mon/x.php
When I use in in wordpress - I never get that working!!
Here is my code:
<?php
$con = mysqli_connect('100.100.25.100','user','Pass123#','pi2w_station');
?>
<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([
['Date', 'Visits'],
<?php
$query = "select TimeStamp,temp_bmp180 from pi2w_attributes order by TimeStamp DESC LIMIT 100";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['TimeStamp']."',".$row['temp_bmp180']."],";
}
?>
]);
var options = {
title: 'Date wise visits'
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
//var chart = new google.visualization.ColumnChart(document.getElementById("columnchart"));
//<div id="columnchart" style="width: 900px; height: 500px;"></div>
chart.draw(data, options);
}
</script>
<div id="curve_chart" style="width: 900px; height: 500px"></div>

Related

How to add latest TimesStamp to Google Gauge

I need help adding latest TimesStamp to page that displays Google gauge. I have made gauge work and auto refresh without the need to refresh the page, but now I need to display on it, or next to it when the latest entry in database was made (displaying TimesStamp of value that is currently displayed in gauge). Here's my code so far:
Chart.html
<!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>
google.charts.load('current', {
packages: ['gauge']
}).then(function () {
var options = {
width: 800, height: 240,
greenFrom: 98, greenTo: 100,
yellowFrom:90, yellowTo: 98,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
drawChart();
function drawChart() {
$.ajax({
url: 'getdata.php',
dataType: 'json'
}).done(function (jsonData) {
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData);
chart.draw(data, options);
// draw again in 5 seconds
window.setTimeout(drawChart, 5000);
});
}
});
</script>
</head>
<body>
<div id="chart_div" style="width: 800px; height: 240px;"></div>
</body>
</html>
And here's getdata.php
<?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4');
$sql = "SELECT ProductPurity FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
// create data array
$data = [];
$data[] = ["Label", "Value"];
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
}
mysqli_close($conn);
// write data array to page
echo json_encode($data);
?>
we need to include the timestamp in the data we return from php.
first, add the field to the select statement, here...
$sql = "SELECT ProductPurity, TimesStamp FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
next, we use a variable to save the timestamp...
// create data array
$data = [];
$data[] = ["Label", "Value"];
$stamp = null;
then, in the while loop, we save the value of the timestamp...
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
$stamp = $row["TimesStamp"]
}
finally, we combine both the chart data and timestamp in an object to send to the page.
$data = array('rows' => $data, 'timestamp' => $stamp);
following is the updated php snippet...
<?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4');
$sql = "SELECT ProductPurity, TimesStamp FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
// create data array
$data = [];
$data[] = ["Label", "Value"];
$stamp = null;
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
$stamp = $row["TimesStamp"]
}
mysqli_close($conn);
// write data array to page
$data = array('rows' => $data, 'timestamp' => $stamp);
echo json_encode($data);
?>
then on the html page, we need to adjust how we receive the data...
to receive the chart data, we need to use the 'rows' property from the data.
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData.rows); // <-- add .rows
and we can receive the timestamp as follows...
jsonData.timestamp
not sure how you want to display the timestamp, here a <div> is used.
so to update the new <div> element...
document.getElementById('timestamp').innerHTML = jsonData.timestamp;
following the updated html snippet...
<!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>
google.charts.load('current', {
packages: ['gauge']
}).then(function () {
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
drawChart();
function drawChart() {
$.ajax({
url: 'getdata.php',
dataType: 'json'
}).done(function (jsonData) {
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData.rows);
chart.draw(data, options);
// update timestamp
document.getElementById('timestamp').innerHTML = jsonData.timestamp;
// draw again in 5 seconds
window.setTimeout(drawChart, 5000);
});
}
});
</script>
</head>
<body>
<div id="timestamp"></div>
<div id="chart_div" style="width: 400px; height: 120px;"></div>
</body>
</html>

Cannot open geojson with leaflet

I am converting my data from database to geojson and then i cant open the returned value from ajax into L.geoJson.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link
rel="stylesheet"
href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css" />
<script
src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-ajax/2.1.0/leaflet.ajax.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div id="map" style="width: 600px; height: 400px"></div>
<script type="text/javascript">
<!-- Base Map -->
var map = L.map('map').setView([40.6430126, 22.934004], 14);
mapLink =
'OpenStreetMap';
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© ' + mapLink + ' Contributors',
maxZoom: 18,
}).addTo(map);
</script>
</body>
</html>
<script>
//Ajax
$.ajax({
method: "GET",
url: "2j.php",
dataType: "json",
}).done(function (data) {
var result = data;
L.geoJson(result).addTo(map);
});
</script>
Php File -> Connection to database and conversation!
<?php
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "basi";
$features = array();
$geojson = array(
'type' => 'FeatureCollection',
'features' => $features
);
$i=1.01;
$conn = new mysqli($servername, $username, $password, $dbname);
// Parse the query into geojson
// ================================================
// ================================================
// Return polygons as GeoJSON
for($i;$i<10;$i++){
$k=floor($i);
$sql = "SELECT x1, y1 FROM afriti where floor(id)=$k";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$feature = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Polygon',
'coordinates' => array((float)$row["x1"], (float)$row["y1"])
));
array_push($features, $feature);
}
}
} echo json_encode($geojson);
?>
I tried just to print something after ajax is done and its doesnt output anything, so either its not ending or something is bad written.
It doesnt print any error messages.
For starters you are missing a parenthesis ) in this line:
'coordinates' => array((float)$row["x1"], (float)$row["y1"]));

Google LineChart mysql with more lines

I'm trying to draw a Google Line Chart but I've some problem drawing the second line. I'm using data from my MySQL database which allow me to display the sum amount of sold pieces grouped by months in 2018.
But I'd like to display the sum amount divided for every responsibility group which is a string value inside my every row.
This is my code:
<?php
$curyear = date('Y');
$con = mysqli_connect('xxxx','xxxx','xxxx','xxxx');
?>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.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 data = google.visualization.arrayToDataTable([
['Date', 'Pezzi',],
<?php
$query = "SELECT responsabile, sum(n_sim)+sum(n_accessi) as pezzi, data_dichiarato FROM dichiarati WHERE responsabile = 'ADMRZ01' and n_ragsoc != 'DICHIARATO ZERO' and YEAR(DATA_DICHIARATO) = '$curyear' GROUP BY MONTH(data_dichiarato) ORDER BY data_dichiarato";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".date("M", strtotime($row['data_dichiarato']))."',".$row['pezzi']."],";
}
?>
]);
// Set chart options
var options = {'title':'SIM CONSEGNATE NEL <?php echo $curyear; ?>',
'width':1200,
'height':300
// isStacked: true
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Divs that will hold the charts-->
<div id="chart_div"></div>
</body>
</html>
So as you can see I have a single query which extracts data just for responsibility ADMRZ01. But in my database, I've rows with ADMRZ02, ADMRZ11, and others.
I'd like to have a line in Linechart for every responsibility I'm adding.
How can I modify my code?
Is it necessary to add another query? Or a Series?
I'm sorry I'm just a beginner in charts
Thanks
in order to have multiple lines / series,
the google data table will need to look something like the following...
var data = google.visualization.arrayToDataTable([
['Date', 'ADMRZ01', 'ADMRZ02', 'ADMRZ11'],
['Jan', 10, 20, 30],
...
]);
but this would very difficult to build from the query, without a bunch of hard-coding
instead, add a column for responsibility,
then we can use google data methods to transform the rows to columns.
to begin, the data table will look something like...
var data = google.visualization.arrayToDataTable([
['Date', 'Responsibility', 'Pezzi'],
['01/01/2018', 'ADMRZ01', 10],
['01/01/2018', 'ADMRZ02', 20],
['01/01/2018', 'ADMRZ11', 30],
['02/01/2018', 'ADMRZ01', 40],
['02/01/2018', 'ADMRZ02', 50],
['02/01/2018', 'ADMRZ11', 60],
['03/01/2018', 'ADMRZ01', 70],
['03/01/2018', 'ADMRZ02', 80],
['03/01/2018', 'ADMRZ11', 90],
]);
you'll want to keep the dates, because when we aggregate,
the month names will get sorted alphabetically, and will be out of order.
e.g. --> Apr, Aug, Dec, Feb, etc...
we can format as month name later.
first, change the query to include all responsibilities...
var data = google.visualization.arrayToDataTable([
['Date', 'Responsabile', 'Pezzi'],
<?php
$query = "SELECT data_dichiarato, responsabile, sum(n_sim)+sum(n_accessi) as pezzi FROM dichiarati WHERE n_ragsoc != 'DICHIARATO ZERO' and YEAR(DATA_DICHIARATO) = '$curyear' GROUP BY data_dichiarato, responsabile ORDER BY data_dichiarato";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['data_dichiarato']."','".$row['responsabile']."'".$row['pezzi']."],";
}
?>
]);
then you can use the following javascript to transform the rows to columns,
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
// create data table
var data = google.visualization.arrayToDataTable([
['Date', 'Responsibility', 'Pezzi'],
['01/01/2018', 'ADMRZ01', 10],
['01/01/2018', 'ADMRZ02', 20],
['01/01/2018', 'ADMRZ11', 30],
['02/01/2018', 'ADMRZ01', 40],
['02/01/2018', 'ADMRZ02', 50],
['02/01/2018', 'ADMRZ11', 60],
['03/01/2018', 'ADMRZ01', 70],
['03/01/2018', 'ADMRZ02', 80],
['03/01/2018', 'ADMRZ11', 90],
]);
// create data view
var view = new google.visualization.DataView(data);
// column arrays
var aggColumns = [];
var viewColumns = [{
// convert string to date
calc: function (dt, row) {
return new Date(dt.getValue(row, 0));
},
label: data.getColumnLabel(0),
type: 'date'
}];
// build view & agg columns for each responsibility
data.getDistinctValues(1).forEach(function (responsibility, index) {
viewColumns.push({
calc: function (dt, row) {
if (dt.getValue(row, 1) === responsibility) {
return dt.getValue(row, 2);
}
return null;
},
label: responsibility,
type: 'number'
});
aggColumns.push({
aggregation: google.visualization.data.sum,
column: index + 1,
label: responsibility,
type: 'number'
});
});
// set view columns
view.setColumns(viewColumns);
// sum view by date
var aggData = google.visualization.data.group(
view,
[0],
aggColumns
);
// draw chart
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(aggData, {
title: 'SIM CONSEGNATE NEL...',
hAxis: {
format: 'MMM',
ticks: view.getDistinctValues(0)
}
});
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
note: jsapi should no longer be used to load the charts library,
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. The last update, for security purposes, was with a pre-release of v45. Please use the new gstatic loader.js from now on.
this will only change the load statement, see above snippet...
<?php
$curyear = date('Y');
$con = mysqli_connect('localhost','root','root','tetra');
?>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Date', 'Pezzi01'],
<?php
$query = "SELECT responsabile, sum(n_sim)+sum(n_accessi) as pezzi01, data_dichiarato FROM dichiarati WHERE responsabile = 'ADMRZ01' and n_ragsoc != 'DICHIARATO ZERO' and YEAR(DATA_DICHIARATO) = '$curyear' GROUP BY MONTH(data_dichiarato), responsabile order by data_dichiarato asc";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".date("M", strtotime($row['data_dichiarato']))."',".$row['pezzi01']."],";
}
?>
]);
var data2 = google.visualization.arrayToDataTable([
['Date', 'Pezzi02'],
<?php
$query = "SELECT responsabile, sum(n_sim)+sum(n_accessi) as pezzi02, data_dichiarato FROM dichiarati WHERE responsabile = 'ADMRZ02' and n_ragsoc != 'DICHIARATO ZERO' and YEAR(DATA_DICHIARATO) = '$curyear' GROUP BY MONTH(data_dichiarato), responsabile order by data_dichiarato asc";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".date("M", strtotime($row['data_dichiarato']))."',".$row['pezzi02']."],";
}
?>
]);
var joinedData = google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]);
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
chart.draw(joinedData, {
height: 300,
width: 600,
interpolateNulls: true,
});
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
</script>
</head>
<body>
<!--Divs that will hold the charts-->
<div id="chart_div"></div>
</body>
</html>
Found another solution with method google.visualization.data.join and it works but I've this silly problem with alphabetical months.

How to display ganttchart with mysql database values in laravel?

I want to make a ganttchart, where I can retrieve data from database using mysql.
Highcharts do no include ganttchart, so i tried google charts. I am able to retrieve values from database and its can be seen in the page source, but not getting the output.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1.1", {packages:["gantt"]});
google.setOnLoadCallback(drawChart);
<?php
$con = mysqli_connect("localhost","root","","db1") or die("could not connect");
$query= "select * from view_chart";
$qresult=mysqli_query($con,$query);
$results = array();
while($res = mysqli_fetch_array($qresult))
{
$results[] = $res;
}
$gan_data = array();
foreach($results as $result)
{
$gan_data[] = ($result['Brands']);
$gan_data1[] = ((int)$result['ratings']);
$gan_data2[] = ((int)$result['bigbazar']);
}
$gan_data = json_encode($gan_data);
$gan_data1 = json_encode($gan_data1);
$gan_data2 = json_encode($gan_data2);
mysqli_free_result($qresult);
?>
function drawChart() {
// var container = document.getElementById('gantt');
//var chart =new google.visualization.GanttChart(container);
alert('hello');
var data = new google.visualization.arrayToDataTable(<?=$gan_data?>);
data.addColumn( type: 'string', id: 'Brands' );
data.addColumn( type: 'number', id: 'ratings' );
data.addColumn( type: 'number', id: 'bigbazar' );
data.addRows([
<?php echo $gan_data; ?>,
<?php echo $gan_data1; ?>,
<?php echo $gan_data2; ?>]);
var options = {
height: 275
};
var chart = new google.visualization.GanttChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>

Data column(s) for axis #0 cannot be of type string?

I am new to this Google charting. I know this question has been asked many times. But all those quiet doesn't seem to solve my problem. So I am posting a fresh one of what my try has been so far.
<?php
$dbhost="localhost";
$dblogin="root";
$dbpwd="";
$dbname="myDB";
$db = mysql_connect($dbhost,$dblogin,$dbpwd);
mysql_select_db($dbname);
$day = date('d');
$month = date('m');
$lastMonth = (string)($month-1);
$lastMonth = strlen($month - 1) == 1? '0'.$lastMonth : $lastMonth;
$SQLString = "SELECT
count(analytics.day) as counts,
analytics.day, month,
date FROM analytics
WHERE year = '2012' AND month = '$month'
OR (month = '$lastMonth' and day > '$day')
GROUP BY day, month
ORDER BY date asc";
$result = mysql_query($SQLString);
$num = mysql_num_rows($result);
# set heading
$data[0] = array('day','counts');
for ($i=1; $i<($num+1); $i++)
{
$data[$i] = array(substr(mysql_result($result, $i-1, "date"), 5, 5),
(int) mysql_result($result, $i-1, "counts"));
}
echo json_encode($data);
mysql_close($db);
?>
Here is the database:
Database
Here is my .html file
<html>
<head>
<title></title>
<!-- Load jQuery -->
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<!-- Load Google JSAPI -->
<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 jsonData = $.ajax({
url: "php/tracker.php",
dataType: "json",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'yet to be decided'
};
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>