How can I output gauge chart and line chart real-time data at the same time, problem is in server.php page?

Viewed 140

I'm stuck at the server.php I have a syntax to fetch sensor_date, sensor_time, and water_level data from the database but dunno how to output it to the line chart like this https://ibb.co/R9RSvkt , the problem is in server.php and it'll only output the gauge chart data (https://ibb.co/rkXPZcR current data of server.php) <-- This is dynamic btw -->

Here's the algorithm to be able to display dynamic and real time gauge chart and line chart.

Index.php

<script src="https://www.gstatic.com/charts/loader.js"></script>
  <script>

    let lineChart, gauge;

<!-- To display two dynamic charts at same time  -->

    const drawChart = arr => {
      if (!lineChart) lineChart = new google.visualization.LineChart(document.getElementById('linechart_div')); // only do this once
      if (!gauge) gauge = new google.visualization.Gauge(document.getElementById('gauge_div')); // only do this once
      var data = google.visualization.arrayToDataTable(arr);
      lineChart.draw(data, lineOptions);
      gauge.draw(data, gaugeOptions);
    }
<!-- To fetch their data from server.php   -->

    const getData = () => {

       fetch('server.php')
         .then(response => response.json())
         .then(arr => {
           drawChart(arr);
           setTimeout(getData, 2000); // run again
         });


    };
    window.addEventListener("load", () => { // when page loads
      google.charts.load('current', {
        'packages': ['gauge','corechart']
      });
      google.charts.setOnLoadCallback(getData); // start
    })


const lineOptions = {
        title: "Sensors Data",
        legend: {
          position: "bottom"
        },
        chartArea: {
          width: "80%",
          height: "70%"
        }
      };
const gaugeOptions  = {
              width: 500,
              height: 200,
              minorTicks: 5,
            };
    


  </script>
</head>

<body>
  

    <div id="gauge_div" style="width: 400px; height: 120px,; margin-top:30px"></div>


    <div id="linechart_div" style="width: 400px; height: 120px,; margin-top:30px;"></div>

</body>

The page below is where the index.php are fetching data, which is only has syntax for the water quality. Currently I don't have an idea how to make syntax for the php to be able to output the db data to the line chart.

Server.php

/*   Use to fetch data from DB for line chart  */
<?php
$connection = mysqli_connect('localhost', 'root', '', 'adminpanel');
$query = 'SELECT temperature, UNIX_TIMESTAMP(CONCAT_WS(" ", sensor_date , sensor_time)) AS datetime
FROM tbl_waterquality ORDER BY sensor_date DESC, sensor_time DESC';

$query_run = mysqli_query($connection, $query);
$rows = array();
$table = array();

$table['cols'] = array(
  array(
    'label' => 'Date Time',
    'type' => 'datetime'
  ),
  array(
    'label' => 'Water Level (ft)',
    'type' => 'number'
  ),
);

while ($row = mysqli_fetch_array($query_run)) {
  $sub_array = array();
  $datetime = explode(".", $row["datetime"]);
  $sub_array[] = array(
    "v" => 'Date(' . $datetime[0] . '000)'
  );
  $sub_array[] = array(
    "v" => $row["temperature"]
  );
  $rows[] = array(
    "c" => $sub_array
  );
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
?>


<?php
error_reporting(E_ALL);
header("content-type: application/json");

$connection = mysqli_connect('localhost', 'root', '', 'adminpanel');
$query = 'SELECT * FROM tbl_waterquality ORDER BY id ASC';
$query_run = mysqli_query($connection, $query);
$row = mysqli_fetch_array($query_run); // assuming ONE result
/*  Fetching water quality data from db  */
$temperature = $row["temperature"];
$pH = $row["pH"];
$DO = $row["DO"];
$turbidity = $row["Turbidity"];

/* this is what the index.php will fetch from this page */
/* Currently this is only for water quality, dunno how can I insert the water level, to be able for them both to show up in one page */
echo <<<EOT
[
["Label", "Value"],
["Temperature", $temperature],
["pH", $pH ],
["DO", $DO ],
["Turbidity", $turbidity ]
],
EOT
?>
1 Answers

If you call server.php not in a browser (i.e. use command line) you'll find that the output is wrong. Alternatively use the networking tools of your browser to view call/response data.

You should apply some basic debugging e.g. check your PHP error logs, always report errors in the javascript fetch(), use networking debug tools in your browser.

Some pointers as you have a few issues:

  1. Using <!-- in PHP code is not correct commenting syntax and will throw and error (check PHP error logs).

  2. Your JSON is incorrect as it ends with a comma. While JavaScript allows them, JSON does not. You will need to catch that error in the fetch() and then display it.

  3. While it won't throw an error as you terminate the script immediately, the HEREDOC syntax is wrong as the closing delimiter should end with semicolon (check error logs).

  4. Ensure that $temperature, $pH etc are JSON friendly. We can';t tell if that causes errors as it depends on contents: regardless it's best to force these to be correct types and "make safe" for JSON.

  5. As you have an HTML comment outside the <?php your output will actually be as below. Again, catch and display errors after your fetch would show this.

    <!--   Use to fetch data from DB for line chart  -->
    
    [
    ["Label", "Value"],
    ["Temperature", $temperature],
    ["pH", $pH ],
    ["DO", $DO ],
    ["Turbidity", $turbidity ]
    ],
    
Related