Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'time' (data from database, data type: timestamp ) for plotting graph in Chart JS

Tags:

html

php

chart.js

a sensor device (temperature sensor) is sending data to database every 10 seconds. I have to plot a graph between time and temperature for one day(latest data). i managed to get data from database. The problem is As I have huge amount of time data as well how to use it to label the Y- axis. date and time is in the form of 2019-04-09 12:28:36. But I can extract the time. But still how to use the time in one (Y)axis. My code shows error Uncaught SyntaxError: Unexpected token :

//php

$sql = "SELECT TIME(Date_Time) as TIME , Temperature FROM dataTable WHERE Date_Time>= (CURDATE() - INTERVAL 1 DAY )  ORDER BY Date_Time DESC ";

$result = $conn->query($sql);
  if ($result->num_rows > 0) {

   while($row = $result->fetch_assoc()) {
     $tempValue =$row['Temperature'];
     $timeInterval=$row['TIME'];

     $tempValues =$tempValues. $tempValue. ',';
     $timeIntervals =$timeIntervals. $timeInterval. ',';
    }
$tempValues =trim ($tempValues, ",");
$timeIntervals= trim ($timeIntervals,"," );

//Javascript

var myChart = document.getElementById('myChart').getContext('2d');




        var data = {
            datasets: [{

            data: [<?php  echo $tempValues ?>],
            backgroundColor: 'transparent',
            borderColor:'rgba(255,99,132)',
            borderWidth:5,
            label: 'Temperature in degree'
          }],

//error in the following line !
          labels: [<?php  echo $timeIntervals ?>]
        };

        var particleChart =new Chart(myChart, {
          type:'line',
          data: data
        });

like image 787
master_yoda Avatar asked Apr 09 '19 13:04

master_yoda


1 Answers

The label must be a string. Build up $timeIntervals this way...

$timeIntervals = $timeIntervals . '"' . $timeInterval . '",';

...in order to have the date-time values wrapped between double quotes.

like image 196
Paolo Avatar answered Nov 12 '22 19:11

Paolo