简体   繁体   English

如何同时输出仪表图和折线图实时数据,问题出在server.php页面?

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

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 -->我被困在 server.php 我有一个语法可以从数据库中获取 sensor_date、sensor_time 和 water_level 数据,但不知道如何将它输出到这样的折线图https://ibb.co/R9RSvkt ,问题是在 server.php 中,它只会输出仪表图数据( https://ibb.co/rkXPZcR server.php 的当前数据)<-- 这是动态 btw -->

Here's the algorithm to be able to display dynamic and real time gauge chart and line chart.这是能够显示动态和实时仪表图和折线图的算法。

Index.php索引.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.下面的页面是 index.php 获取数据的地方,它只有水质的语法。 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.目前我不知道如何为 php 制作语法以便能够将 db 数据输出到折线图。

Server.php服务器.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
?>

If you call server.php not in a browser (ie use command line) you'll find that the output is wrong.如果您不在浏览器中调用 server.php(即使用命令行),您会发现输出是错误的。 Alternatively use the networking tools of your browser to view call/response data.或者,使用浏览器的网络工具查看呼叫/响应数据。

You should apply some basic debugging eg check your PHP error logs, always report errors in the javascript fetch(), use networking debug tools in your browser.你应该应用一些基本的调试,例如检查你的 PHP 错误日志,总是在 javascript fetch() 中报告错误,在浏览器中使用网络调试工具。

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).在 PHP 代码中使用<!--是不正确的注释语法,会抛出错误(检查 PHP 错误日志)。

  2. Your JSON is incorrect as it ends with a comma.您的 JSON 不正确,因为它以逗号结尾。 While JavaScript allows them, JSON does not.虽然 JavaScript 允许它们,但 JSON 不允许。 You will need to catch that error in the fetch() and then display it.您需要在 fetch() 中捕获该错误,然后显示它。

  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).虽然它不会在您立即终止脚本时抛出错误,但 HEREDOC 语法是错误的,因为结束分隔符应以分号结尾(检查错误日志)。

  4. Ensure that $temperature , $pH etc are JSON friendly.确保$temperature$pH等是 JSON 友好的。 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.我们无法判断这是否会导致错误,因为它取决于内容:无论如何最好将这些强制为正确的类型并为 JSON“确保安全”。

  5. As you have an HTML comment outside the <?php your output will actually be as below.由于您在<?php之外有一个 HTML 注释,因此您的输出实际上如下所示。 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 ] ],

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM