簡體   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?

我被困在 server.php 我有一個語法可以從數據庫中獲取 sensor_date、sensor_time 和 water_level 數據,但不知道如何將它輸出到這樣的折線圖https://ibb.co/R9RSvkt ,問題是在 server.php 中,它只會輸出儀表圖數據( https://ibb.co/rkXPZcR server.php 的當前數據)<-- 這是動態 btw -->

這是能夠顯示動態和實時儀表圖和折線圖的算法。

索引.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>

下面的頁面是 index.php 獲取數據的地方,它只有水質的語法。 目前我不知道如何為 php 制作語法以便能夠將 db 數據輸出到折線圖。

服務器.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
?>

如果您不在瀏覽器中調用 server.php(即使用命令行),您會發現輸出是錯誤的。 或者,使用瀏覽器的網絡工具查看呼叫/響應數據。

你應該應用一些基本的調試,例如檢查你的 PHP 錯誤日志,總是在 javascript fetch() 中報告錯誤,在瀏覽器中使用網絡調試工具。

一些指針,因為你有幾個問題:

  1. 在 PHP 代碼中使用<!--是不正確的注釋語法,會拋出錯誤(檢查 PHP 錯誤日志)。

  2. 您的 JSON 不正確,因為它以逗號結尾。 雖然 JavaScript 允許它們,但 JSON 不允許。 您需要在 fetch() 中捕獲該錯誤,然后顯示它。

  3. 雖然它不會在您立即終止腳本時拋出錯誤,但 HEREDOC 語法是錯誤的,因為結束分隔符應以分號結尾(檢查錯誤日志)。

  4. 確保$temperature$pH等是 JSON 友好的。 我們無法判斷這是否會導致錯誤,因為它取決於內容:無論如何最好將這些強制為正確的類型並為 JSON“確保安全”。

  5. 由於您在<?php之外有一個 HTML 注釋,因此您的輸出實際上如下所示。 同樣,在您提取后捕獲並顯示錯誤會顯示這一點。

     <!-- 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