I am trying to use a MySQL TimeStamp for the X Axis on a Scatter graph using Google Charts. Currently, the only way I have managed to get the graph displaying it using the strtotime() Function. This confuses the graph or me as strtotime() Function shows a number of seconds from 1st Jan 1970.
new Date(2017-03-07 02:03:12)] YYYY-MM-DD HH:ii:SS this is the format of the date coming from my timestamp if I leave it like this then I get the error. only if I change the time to the strtotime() this works. But the Graph does not show the time properly. Is there another way to display the timestamp. As the Documentation on google does not make much sense.
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Distance');
data.addColumn('datetime', 'time');
data.addRows([
<?php
$query = "SELECT * FROM iot_sensors WHERE Sensor_ID ='Ultra_Dist'";
$execute = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($execute)){
$date = strtotime($row['Time_Stamp']);
echo "[".$row['Sensor_1'].", new Date(".$date.")],";
$Trimmed = trim($row['Time_Stamp']);
//echo $Trimmed;
}
?>
]);
var options = {
width: 800,
height: 500,
chart: {
title: 'Frequency of movement by time',
subtitle: 'Frequency of movement'
},
hAxis: {title: 'Distance'},
vAxis: {title: 'time'}
};
This is my code which retrieves the Time_Stamp and other value from my table and puts it in an array for the chart to use.
<?php
$query = "SELECT * FROM iot_sensors WHERE Sensor_ID ='Ultra_Dist'";
$execute = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($execute)){
$date = ($row['Time_Stamp']);
$date2 = new DateTime($date);
$date3 = date_format($date2, 'Y,m,d,H,i,s');
echo "[new Date(".$date3."),".$row['Sensor_1']."],";
}
?>
Put the date in a new Date() object then reformat it to the accepted format and then echo the date in the array.
Related
I'm creating a table using Google Table Charts and PHP.
The table code is:
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(drawTable);
function drawTable() {
var data = google.visualization.arrayToDataTable([
<?php echo $dados; ?>
]);
var table = new google.visualization.Table(document.getElementById('table_div'));
data.sort({column: 0, desc: true});
table.draw(data, {showRowNumber: false, width: '100%', height: '100%'});
}
The PHP code (that gets the data) is:
$dados = "['Data','InfoX','InfoY'],";
for($i = 0; $i < count($vet); $i++){
$original_Date = $vet[$i][0];
$New_Date = date("d/m/Y", strtotime($original_Date));
$dados .= "['".$New_Date."',".$vet[$i][2].",".$vet[$i][3].','."]";
if ($i+1 < count($vet)){
$dados .= ",";
}
Currently, the table looks like this:
As you can see, I have a problem with the way the first column is sorted (right now, it is ordering first by the day, then the month and the year).
I need to order the first column chronologically (year-month-day), but show it in a dd/mm/yyyy format (in HTML, it is like when you use data-search and data-order). Is there any option custom propriety or option that I need to use to solve my issue?
Thanks in advance for the answers and feel free to ask for more details if you need it.
the problem is the dates are coming across as strings.
with real dates, the sort function will work correctly.
try using the following php...
$New_Date = date("m/d/Y", strtotime($original_Date));
$dados .= "[new Date('".$New_Date."'),".$vet[$i][2].",".$vet[$i][3].','."]";
then in javascript, use a date formatter to format the date column...
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(drawTable);
function drawTable() {
var data = google.visualization.arrayToDataTable([
<?php echo $dados; ?>
]);
var table = new google.visualization.Table(document.getElementById('table_div'));
data.sort({column: 0, desc: true});
var formatDate = new google.visualization.DateFormat({pattern: 'dd/MM/yyyy'});
formatDate.format(data, 0);
table.draw(data, {showRowNumber: false, width: '100%', height: '100%'});
}
I have a line chart with dynamic data make by c3js chart library.
In that chart, I already show data depend on date with timeseries. Here is the sample of chart.
Now I add three button to show data in chart by day,month and year. When I click day button, I want to show data only day by day. And the year and month button are also too.
The main point is, I want to change x-axis date format dynamically when I click day, month and year button.
So I query data from database for each day, month and year. But the problem is, when I show data in chart, I need to change date format dynamically in x-axis. So, I try like this,
<?php
if(isset($_POST['btn_day'])) {
$sql = "......."
$query = ........;
//query data day by day just like DATE_FORMAT(date, '%d') as date
.
$format = '%d';
}elseif(isset($_POST['btn_month'])) {
$sql = "......."
$query = ........;
//query data for each month just like DATE_FORMAT(date, '%M') as date
.
$format = '%m';
}elseif(isset($_POST['btn_year'])) {
$sql = "......."
$query = ........;
//query data for each year just like DATE_FORMAT(date, '%Y') as date
.
$format = '%Y';
}else {
$sql = "......."
$query = ........;
.
.
$format = '%Y-%m-%d';
}
?>
<script>
var f = <?php echo "'".$format."'"?>; //'%Y-%m-%d'
console.log(f);
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'date',
json:<?php echo json_encode($data);?>,
mimeType: 'json',
keys: {
x: 'date',
value: <?php echo json_encode($names)?>
},
type: 'line',
},
axis: {
x: {
type: 'timeseries',
tick:{
format: function(f){
if(f == "%d"){
return d3.getDay();
}else if(f == "%m"){
return d3.getMonth();
}else if(f == "%Y"){
return d3.getFullYear();
}else{
return '%Y-%m-%d';
}
},
rotate: 75,
}
}
},
});
</script>
But I don't get correct result in chart. I know I was wrong in this part,
tick:{
format: function(f){
if(f == "%d"){
return d3.getDay();
}else if(f == "%m"){
return d3.getMonth();
}else if(f == "%Y"){
return d3.getFullYear();
}else{
return '%Y-%m-%d';
}
},
rotate: 75,
}
But I don't know how can I change x-axis date format dynamically. I already try a lot of way but I can't get correct result.
I very appreciate for any suggestion.
d3 doesn't have getDay() / getMonth() / getFullYear() functions, what you need (if f exists) is
d3.time.format(f)
See https://github.com/mbostock/d3/wiki/Time-Formatting
(Moreover, you're not really changing the formatting dynamically as far as the chart is concerned, you're generating a new c3 chart each time, though that's probably just semantics.)
I am trying to plot xaxis in Flot-chart with date. i have tried with configuring xaxis and also using javascript EPOCH but still no success, here is my piece of code.
<?php
foreach($data[0] as $i => $d){
foreach ($d as $key => $value) {
$data[0][$i][$key][0] = strtotime($value[0]);
}
}
$data1 = json_encode($data[0][0]);
$data2 = json_encode($data[0][1]);
echo $data1;
/* print $data1 will give this */
[[1367605800,"0.006"],[1367692200,"0.012"],[1367778600,"0.394"],[1367865000,"0.509"],[1367951400,"0.000"],[1368037800,"0.032"],[1368124200,"0.000"]]
/*for checking purpose */
$json = json_decode($data1);
foreach ($json as $key => $val) {
$readabledate = date("m-d-Y", $val[0]).'<br>';
echo $readabledate;
}
/* after decoding 1367605800,1367692200,... i get date in readable format again thsis is what i need in xaxis
05-05-2013
05-06-2013
05-07-2013
05-08-2013
05-09-2013
05-10-2013
*/
?>
<script>
$(function () {
/**
* Flot charts data and options
*/
var data1 = <?php echo $data1;?>;
var data2 = <?php echo $data2;?>;
/*checking static date values */
var date = new Date(1367605800*1000);
alert(date);
//Sat May 04 2013
/*alert showing 1367605799.2 value
ends here*/
var chartUsersOptions = {
grid: {
tickColor: "#f0f0f0",
borderWidth: 1,
borderColor: 'f0f0f0',
color: '#6a6c6f'
},
xaxis: {
mode: "time",
timeformat: "%Y/%m/%d",
minTickSize: [1, "day"]
},
colors: [ "#62cb31", "#efefef"],
};
$.plot($("#flot-line-chart"), [data1, data2], chartUsersOptions);
});
</script>
if i remove minTickSize: [1, "day"] from xaxis config its plotting 1970/01/16 in xaxis. where i am wrong or how it can be done. please suggest
i figured out the solution, basically javascript epoch is calculating time by multiplying it with 1000 which i have shown by taking a static value.
var data1 = <?php echo $data1;?>;
var data2 = <?php echo $data2;?>;
/*checking static date values */
var date = new Date(1367605800*1000);
alert(date);
//Sat May 04 2013
so to do this with the whole var data1 i just need to multiply $data[0][$i][$key][0] = strtotime($value[0])*1000; in my php code. that's it problem solved. Cheers..
I want to show employee data in pie chart. I'm able to make pie chart using jQuery and php. But demand is that in a page there are 12 button. Name Jan to Dec.
When user click on feb then pie chart of feb is shown to user. When click on dec the pie chart of dec. is shown to user.
In my database there is a date column where date is stored like 2015-06-23
I'm not able to get logic of SQL query here is my code but it need improvements.
<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 = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows
([
<?php
$servername = "localhost";
$username = "root";
$dbname = "dat_database";
$password = "";
$conn = new mysqli($servername, $username, $password, $dbname);
$EMP_ID = 'MMUM254';
$sql = "SELECT typeof_task,hourspend from emp_dat_info where EMP_ID='" . $EMP_ID. "' ORDER BY date DESC LIMIT 10 " ;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$a[] = "['" . $row["typeof_task"] . "', " . $row["hourspend"] . "]";
}
echo implode(', ', $a);
}
?>
]);
// Set chart options
var options = {'title':'How Much Hours You Spend',
'width':900,
'height':500};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
<?php echo date("Y"); ?>
`
You can try month clause in your code to get only month data
$sql = "SELECT typeof_task,hourspend
FROM emp_dat_info
WHERE EMP_ID='" . $EMP_ID. "'
ORDER BY MONTH(date) DESC LIMIT 10 " ;
$result = $conn->query($sql);
If you want to get the full name of the month then you can try MONTHNAME clause in the query. Pass the date in the MONTHNAME clause.
$sql = "SELECT typeof_task,hourspend
FROM emp_dat_info
WHERE EMP_ID='" . $EMP_ID. "'
ORDER BY MONTHNAME(date) DESC LIMIT 10 " ;
$result = $conn->query($sql);
For more reference you can visit this link : https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_month
Try MONTH with date
$sql = "SELECT typeof_task,hourspend
FROM emp_dat_info
WHERE EMP_ID='" . $EMP_ID. "'
ORDER BY MONTH(date) DESC LIMIT 10 " ;
$result= $conn->query($sql);
I am using Highcharts to display a chart containing dates/time and temperature of a room.
The javascript used to generate the chart is in the temperature.php file which user will be able to view, and the javascript will get data from a dataSorter.php file which contains SQL query to retrieve the results from MySQL for the chart to display.
Javascript to generate the chart in temperature.php:
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 50
},
title: {
text: 'Temperature vs. Time',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Degrees Celcius'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("dataSorter.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
</script>
At this point, I have generated 4 drop down lists in temperature.php containing From Date, To Date, From Time and To Time. This will allow users to select a range which they wish to see the chart generate. (E.g 2014-01-20 00:00:00 to 2014-01-21 22:00:00). A button onclick will activate the function:
if(isset($_POST['sort'])){
$from=$_POST['SDate'];
$to=$_POST['EDate'];
$sTime=$_POST['STime'];
$eTime=$_POST['ETime'];
$start=$from." ".$sTime;
$end=$to." ".$eTime;
header('Location: dataSorter.php?start='.$start.'&end='.$end.'');
}
?>
$from = start date
$to = end date
$sTime = start time
$eTime = end time
$start = combine $from and $sTime to get a start date/time
$end = combine $to and $eTime to get a end date/time
dataSorter.php has the following codes:
<?php
$con = mysql_connect("localhost","root","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("scsense", $con);
if(isset($_GET['start'])){
$start = $_GET['start'];
$end = $_GET['end'];
$sth = mysql_query("SELECT * FROM scsenseinfo WHERE roomID='501' AND (dateTime BETWEEN '$start' AND '$end') ORDER BY recordID");
$rows = array();
$rows['name'] = 'DateTime';
while($rr = mysql_fetch_assoc($sth)) {
$rows['data'][] = $rr['dateTime'];
}
$sth = mysql_query("SELECT * FROM scsenseinfo WHERE roomID='501' AND (dateTime BETWEEN '$start' AND '$end') ORDER BY recordID");
$rows1 = array();
$rows1['name'] = 'RoomTemperature';
while($r = mysql_fetch_array($sth)) {
$rows1['data'][] = $r['roomTemp'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
$help = print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
}
else{
$sth = mysql_query("SELECT * FROM (SELECT * FROM scsenseinfo WHERE roomID='501' ORDER BY recordID DESC LIMIT 5) AS tbl ORDER BY tbl.recordID ASC");
$rows = array();
$rows['name'] = 'DateTime';
while($rr = mysql_fetch_assoc($sth)) {
$rows['data'][] = $rr['dateTime'];
}
$sth = mysql_query("SELECT * FROM (SELECT * FROM scsenseinfo WHERE roomID='501' ORDER BY recordID DESC LIMIT 5) AS tbl ORDER BY tbl.recordID ASC");
$rows1 = array();
$rows1['name'] = 'RoomTemperature';
while($r = mysql_fetch_array($sth)) {
$rows1['data'][] = $r['roomTemp'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
$help = print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
}
//header('Location: L501TempSorter.php');
?>
If I have header('Location: L501TempSorter.php'); un-commented, the chart does not display a thing, even when onload of the page, without clicking the button to sort the dates. If it is commented, the chart is displayed onload, but clicking the button to sort the dates lead to dataSorter.php and stays on the page, which just displays the arrays containing the sorted dates. I really need help with this, thank you in advance!
You cannot use header when you have already printed something, like you sdo with //header('Location: L501TempSorter.php');.
If you are trying to save the output from print to the variable $help than you need to use sprint instead. Print will always output to the output buffer and always returns 1. This is true for any print function not starting with a s or vs the s before the print in the function name always indicates that it will return the resulting string instead of outputting it.
To solve your problem with the data not being displayed please post the onlcick code of the button. It should be an ajax call like
<script>
$.getJSON('dataSorter.php', {
sort: 'sortValue',
STime: /* get start value */,
ETime: /* get end value */,
SDate: /* get start value */,
EDate: /* get end value */
}, function(data) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
/* or anything that updates your chart */
});
</script>
In the php script run when the onClick function is executed. You should probably url encode your Location: in part
<?php
header('Location: dataSorter.php?start='.urlencode($start).'&end='.urlencode($end));
Though I don't understand why you are using header('Location: ...'); here anyways? You are already on the Server why tell the client browser to load a different location just include your script that is supposed to run now.
What is your purpose of using location, in case when you use this script only for return json? When you load json in javascirpt, you run your entire php script, so instead od returning json you are redirect to other location, as a result json is not loaded in javascript.