How make a growth baby chart with data in mysql +PDO - mysql

I am trying to make a chart with growth baby table I have in DB... I lost the idea and right now I don't know how to do it... this is the chart I need to show when the doctor insert the height and weight of every child...need to show the inserted the percentiles data and that will depend of the height and weight of the baby to show the graph (gray line)...
here is my code until now (EDITED WITH NEW CODE):
<?php
include 'includes/configs.php';
/*
* $normal is an array of (edad => peso) key/value pairs
* $desnutricion is an array of (edad => peso) key/value pairs
* $desnutricionSevera is an array of (edad => peso) key/value pairs
*
* you can hard-code these or pull them from a database, whatever works for you
*/
$sql = $conn->prepare("SELECT * FROM ESTATURA WHERE edad<>'' AND peso<>'' AND id_paciente = 1");
$sql->execute();
$data = array(array('Meses', $apellido, 'Normal', 'Desnutricion', 'Desnutricion Severa'));
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$edad = $row['edad'];
// use (int) to parse the value as an integer
// or (float) to parse the value as a floating point number
// use whichever is appropriate
$edad = (int) preg_replace('/\D/', '', $edad);
$peso = $row['peso'];
$peso = (float) preg_replace('/\D/', '', $peso);
$data[] = array($peso, $edad, $normal[$edad], $desnutricion[$edad], $desnutricionSevera[$edad]);
$data1[] = array($peso, $edad);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> </title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<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([<?php echo json_encode($data); ?>]);
// sort the data by "Meses" to make sure it is in the right order
data.sort(0);
var options = {
title: 'Grafica de Crecimiento de niñas de 0 a 24 meses',
hAxis: {
title: 'Meses',
titleTextStyle: {color: '#333'}
},
vAxis: {
minValue: 0
},
series: {
0: {
<?php echo implode(",", $peso); ?>
type: 'line'
},
1: {
// series options for normal weight
type: 'area'
},
2: {
// series options for desnutricion
type: 'area'
},
3: {
// series options for desnutricion severa
type: 'area'
}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 800px; height: 400px;"></div>
</body>
</html>
I don't understand how can insert the default variables (normal, desnutricion and desnutricion severa) with the baby variable.. I need to create a new table with the defaults data and then make a union? or just insert the variables in every series??
--OLD CODE--
<?php
include 'includes/configs.php';
$sql = $conn->prepare("SELECT nombre, apellido, edad, peso FROM ESTATURA WHERE edad<>'' AND peso<>'' ");
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$nombre = trim(addslashes($row['nombre']));
$lapellido = trim(addslashes($row['apellido']));
$edad = $row['edad'];
$edad = preg_replace('/\D/', '', $edad);
$peso = $row['peso'];
$peso = preg_replace('/\D/', '', $peso);
$myurl[] = "['".$nombre." ".$apellido."', ".$edad.",".$peso."]";
}
print_r($myurl);
echo implode(",", $myurl);
?>
<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([
['Meses', 'Normal', 'Desnutrición', 'Desnutrición Severa'],
/*['0', 4.23, 2.39, 2.00],
['1', 5.55, 3.10, 2.85],
['2', 6.75, 3.95, 3.41],
['3', 7.60, 4.50, 4.00],
['4', 8.23, 5.00, 4.40],
['5', 8.81, 5.38, 4.80],
['6', 9.30, 5.71, 5.11],
['7', 9.87, 6.00, 5.38],
['8', 10.19, 6.21, 5.58],
['9', 10.56, 6.47, 5.76],
['10', 10.95, 6.66, 5.95],
['11', 11.20, 6.80, 6.10],
['12', 11.55, 7.00, 6.21],
['13', 11.91, 7.20, 6.40],
['14', 12.10, 7.38, 6.58],
['15', 12.37, 7.54, 6.77],
['16', 12.60, 7.75, 6.85],
['17', 12.96, 7.86, 7.00],
['18', 13.16, 8.05, 7.20],
['19', 13.41, 8.20, 7.31],
['20', 13.72, 8.38, 7.42],
['21', 14.02, 8.49, 7.61],
['22', 14.24, 8.70, 7.79],
['23', 14.68, 8.90, 7.95],
['24', 14.90, 9.00, 8.00]*/
<?php echo implode(",", $myurl); ?>
]);
var options = {
title: 'Grafica de Crecimiento de niñas de 0 a 24 meses',
hAxis: {title: 'Meses', titleTextStyle: {color: '#333'}},
vAxis: {minValue: 0}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="width: 800px; height: 400px;"></div>
inside of /*.....*/ is the percentiles that I need to show with the data in mysql...but I comented because the chart is not shown when that data don't have /*...*/
here the chart right now..
can you help me with my type of chart?
Best Regards
Andrés Valencia

This is the basic framework you will need to make this work:
/*
* $normal is an array of (edad => peso) key/value pairs
* $desnutricion is an array of (edad => peso) key/value pairs
* $desnutricionSevera is an array of (edad => peso) key/value pairs
*
* you can hard-code these or pull them from a database, whatever works for you
*/
$sql = $conn->prepare("SELECT edad, peso FROM ESTATURA WHERE <criteria to select baby>");
$sql->execute();
$data = array(array('Meses', $apellido, 'Normal', 'Desnutricion', 'Desnutricion Severa'));
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$edad = $row['edad'];
// use (int) to parse the value as an integer
// or (float) to parse the value as a floating point number
// use whichever is appropriate
$edad = (int) preg_replace('/\D/', '', $edad);
$peso = $row['peso'];
$peso = (float) $peso;
$data[] = array($edad, $peso, $normal[$edad], $desnutricion[$edad], $desnutricionSevera[$edad]);
}
Then, in your javascript:
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo json_encode($data); ?>);
// sort the data by "Meses" to make sure it is in the right order
data.sort(0);
var options = {
title: 'Grafica de Crecimiento de niñas de 0 a 24 meses',
hAxis: {
title: 'Meses',
titleTextStyle: {color: '#333'}
},
vAxis: {
minValue: 0
},
series: {
0: {
// series options for this babys weight
type: 'line'
},
1: {
// series options for normal weight
type: 'area'
},
2: {
// series options for desnutricion
type: 'area'
},
3: {
// series options for desnutricion severa
type: 'area'
}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Give that a try and see if it works for you.

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>

How can I populate Google line chart with data from mySQL database. (single file / Inline solution)

I have an MCU (ESP8266) with a temperature and humidity sensor.
The MCU sends the measurement data via MQTT to an MQTT broker running on my Synology NAS.
Also running on the NAS is an MQTT client (Node.js) that writes the received data to the MySQL database on the NAS.
Last but not least, a web server and PHP server are also running on the NAS.
Now I want to make a website to display the data from the db as a line chart.
Questions:
How can I populate Google line chart with data from mySQL database?
It's possible to use one single file (.php) to do this?
How can I manage a date range selection?
How can i select / deselect lines on the chart?
Here my answer to my question.
Since I have no big idea of the used programming languages, I had to search, read and test a lot of sources in the web to copy the result together :-)
I will extend it a bit in future, but for me it works perfectly.
I would like to present this solution here to help others get started.
However, there are certainly many ways to improve the code.
If someone wants to, I'd be happy about suggestions.
Complete File on Github.
https://github.com/DIYDave/MySQL-and-Google-Line-Chart
PHP. Read the data from the db and returns a JSON string to javascript
<?php
function getData(){
// Connect to MySQL (db Hostname/IP, user, password, database)
$link = new mysqli( '192.168.10.10', 'user', 'password', 'mymqttdb' );
if ( $link->connect_errno ) {
die( "Failed to connect to MySQL: (" . $link->connect_errno . ") " . $link->connect_error );
}
$start = $_GET['startDate']; // Get parameter from URL
$ende = $_GET['endDate']; // Get parameter from URL
if (!isset($endDate )){ // No end date? then actual for end
$endDate = date('Y-m-d H:i', time());
}
if (!isset($startDate )){ // No start date? then actual -1 day for start
$startDate = date('Y-m-d H:i', strtotime('-1 day', strtotime($ende)));
}
// Query in SQL ! add your own columns and database table name!
$query= "SELECT `DateTime`,`temperature`,`humidity` FROM `Chickenhouse` WHERE `DateTime` BETWEEN" . "'" . $startDate ."'" . "AND" . "'" . $endDate ."'";
$result = $link->query($query); // make db query
$rows = array();
$table = array();
$table['cols'] = array
(
array('label' => 'Date Time', 'type' => 'datetime'),
array('label' => 'Temperatur (°C)', 'type' => 'number'), // Select your label for the index
array('label' => 'Luftfeuchtigkeit (%)', 'type' => 'number') // Select your label for the index
);
while($row = mysqli_fetch_array($result)) // got to all the lines of the query result
{
$sub_array = array();
$date1 = new DateTime($row['DateTime']);
$date2 = "Date(".date_format($date1, 'Y').", ".((int) date_format($date1, 'm') - 1).", ".date_format($date1, 'd').", ".date_format($date1, 'H').", ".date_format($date1, 'i').", ".date_format($date1, 's').")";
$sub_array[] = array("v" => (string)$date2);
$sub_array[] = array("v" => $row["temperature"]);
$sub_array[] = array("v" => $row["humidity"]);
$rows[] = array("c" => $sub_array);
}
$table['rows'] = $rows;
$lineCount = count($rows); // Number of array fields (lines) to show in browser
return array(json_encode($table), $lineCount); // Make JSON from array and give it to the java script together with linecount
}
?>
CSS and HTML. More or less just for formatting and setting placeholders.
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.2.3/flatpickr.css">
<style>
*{font-family:Arial;}
.page-wrapper{ width:90%; margin:0 auto; }
input { border: 2px solid whitesmoke;border-radius: 12px; padding: 12px 10px; text-align: center; font-size: 16px; font-weight: bold; width: 250px;background: cornflowerblue; color: yellow;}
button { border: none; border-radius: 10px; text-align: center; padding: 12px 10px; cursor: pointer; font-weight: bold; background: cornflowerblue; color: white;}
</style>
</head>
<body>
<div class="page-wrapper"> </div>
<input type="text" style="float:left" id="rangeDate" placeholder="Select Timespan" data-input>
<br>
<p id="LineCount" > </p>
<div id="line_chart" style="width: 100%; height: 800px"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.2.3/flatpickr.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
Javascript. Google chart. Accepts the JSON data and displays it as a line diagram. Here are many options possible.
Details here: https://developers.google.com/chart/interactive/docs/gallery/linechart
// Setup and show Google line chart
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable(<?php echo getData()[0]?>); // Call PHP-Function an receive JSON
document.getElementById("LineCount").innerHTML= " " + <?php echo getData()[1]?> + " Records loaded"; // Get record count
var options = {
series: {
0:{color: 'red', visibleInLegend: true, targetAxisIndex: 0},
1:{color: 'blue', visibleInLegend: true, targetAxisIndex: 1}
},
vAxes: {
// Adds labels to each axis; they don't have to match the axis names.
0: {title: 'Temp (°C)' }, // , 'minValue': 0, 'maxValue': 30
1: {title: 'Feuchte(%)'}
},
title:'Chickenhouse',
legend:{position:'top'},
chartArea:{width:'75%', height:'65%'},
//curveType: 'function',
hAxis: {
title: 'Datum', titleTextStyle: {color: '#333'},
format: 'd.M HH:mm',
slantedText:true, slantedTextAngle:80
},
explorer: {
actions: ['dragToPan', 'dragToZoom', 'rightClickToReset'], // 'dragToZoom'
axis: 'horizontal',
keepInBounds: true,
maxZoomIn: 28.0,
maxZoomOut: 1.0,
zoomDelta: 1.5
},
colors: ['#D44E41'],
};
var date_formatter = new google.visualization.DateFormat({ // Tooltip format
pattern: "dd.MM.yyyy - HH:mm"
});
date_formatter.format(data, 0);
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
Javascript. Selection of displayed lines by clicking on the legend.
// Select / deselect lines by clicking on the label
var columns = [];
var series = {};
for (var i = 0; i < data.getNumberOfColumns(); i++) {
columns.push(i);
if (i > 0) {
series[i - 1] = {};
}
}
google.visualization.events.addListener(chart, 'select', function () {
var sel = chart.getSelection();
// if selection length is 0, we deselected an element
if (sel.length > 0) {
// if row is undefined, we clicked on the legend
if (sel[0].row === null) {
var col = sel[0].column;
if (columns[col] == col) {
// hide the data series
columns[col] = {
label: data.getColumnLabel(col),
type: data.getColumnType(col),
calc: function () {
return null;
}
};
// grey out the legend entry
series[col - 1].color = '#CCCCCC';
} else {
// show the data series
columns[col] = col;
series[col - 1].color = null;
}
var view = new google.visualization.DataView(data);
view.setColumns(columns);
chart.draw(view, options);
}
}
});
};
Javascript. Flatpickr. Cool javascript app to select date and time. It's also possible to select date ranges what I use here. https://flatpickr.js.org/
// Flatpickr to select date range
$("#rangeDate").flatpickr({
enableTime: false,
mode: 'range',
time_24hr: true,
dateFormat: "Y-m-d",
maxDate: "today",
defaulDate: "today",
onClose: function test(selectedDates, dateStr, instance){
arDateTime = dateStr.split(" to ");
dateTimeStart = arDateTime[0] + " 00:00" ;
dateTimeEnd = arDateTime[1] + " 23:59" ;
strNeu = "?startDate=" + dateTimeStart + "&endDate=" + dateTimeEnd;
window.location = strNeu;
},
});
Complete File on Github.
https://github.com/DIYDave/MySQL-and-Google-Line-Chart
Result:
Screenshot

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>

Google Org Chart - Draw a chart from JSON (mysql)

I'm trying to draw an organizational chart (http://goo.gl/wgftfO) from JSON (php - mysql) but it doen'st display well.
Here is my HTML code:
<script type="text/javascript">
google.load('visualization', '1', {packages:['orgchart']});
google.setOnLoadCallback(drawChart);
function json(){
$.ajax({
type: "POST",
url: "function/ver.php",
success: function(datos){
datos = eval(datos);
for (var i=0;i<datos.length;i++){
var id = datos[i].id;
var nombre = datos[i].nombre;
var jefe = datos[i].jefe;
alert(id);
drawChart(id, nombre);
function drawChart(id, nombre) {
//alert("Id: " + id + " | Nombre: " + nombre);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
data.addRows([
[nombre, jefe, id]
]);
var chart = new google.visualization.OrgChart(document.getElementById('contenido'));
chart.draw(data, {allowHtml:true});
}
}
},
error: function(error){
alert(error);
}
});
}
</script>
</head>
<body onLoad="json()">
<div id="contenido"></div>
</body>
JSON result:
[
{
"id":"1",
"nombre":"Andrey",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-G1-icon.png",
"jefe":""
},
{
"id":"2",
"nombre":"Enrique",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-F3-icon.png",
"jefe":"Andrey"
},
{
"id":"3",
"nombre":"Chero",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-E4-icon.png",
"jefe":"Andrey"
},
{
"id":"4",
"nombre":"Ricardo",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-F3-icon.png",
"jefe":"Chero"
},
{
"id":"5",
"nombre":"Jhon",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-H1-icon.png",
"jefe":"Enrique"
}
]
This displays like:
And, if i remove the alert(id) form the HTML code (in ajax), just shows the last object of the JSON:
How can i fix this?
or, is there any other option to do this chart?
Thank your for answers
The bellow code worked for me
index.html
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript' src='js/jquery.min.js'></script>
<script type='text/javascript'>
google.load('visualization', '1', { packages: ['orgchart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "ajax/organization.php",
success: function(result){
var result = JSON.parse(result);
if ((emp_count = result.length) > 0) {
console.log(result);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addRows(emp_count);
for (i = 0; i < emp_count; i++) {
data.setCell(i, 0, result[i].emp);
data.setCell(i, 1, result[i].manager);
}
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
chart.draw(data, { allowHtml: true });
}
}
});
}
</script>
organization.php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'USERNAME');
define('DB_PASSWORD', 'PASSWORD');
define('DB_DATABASE', 'DATABASE_NAME');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
$query=mysql_query("select emp, manager from employees") or die(mysql_error());
# Collect the results
while($obj = mysql_fetch_object($query)) {
$arr[] = $obj;
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;