简体   繁体   English

数据库中的数据 --> 到 json 数组 in.php --> 这个数组到 in.js 表中,然后通过调用 .js 文件在.html 中可视化

[英]Data from database --> to json array in .php --> this array into table in .js and then visualise it in .html by calling .js file

I have to take data from my database and show it in table in data.html + google chart.我必须从我的数据库中获取数据并将其显示在 data.html + google 图表中的表格中。 So basically my html has to call script.js file which is using read.php as API to extract the data out my database.所以基本上我的 html 必须调用 script.js 文件,该文件使用 read.php 作为 API 从我的数据库中提取数据。

My html file is ok i think.我认为我的 html 文件没问题。 But im so stuck with.js and.php files.但我非常坚持使用 .js 和 .php 文件。

I need help how to store data from database into.php file and then use that data in.js file to add rows in my html table.我需要帮助如何将数据库中的数据存储到 .php 文件中,然后使用该数据 in.js 文件在我的 html 表中添加行。

Please help guys.请帮助伙计们。

<?php

$dbhost = 'localhost';
$dbuser = 'webuser';
$dbpass = 'secretpassword';
$dbname = 'iot_website';

$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

?>


<?php

$result_set = mysqli_query($connection, "SELECT * FROM sensor_data ORDER BY id DESC LIMIT 100");

?>


<?php    

$results = []; //new blank array ready for populating with row data

while($res = mysqli_fetch_array($result_set)) {
  $results[] = $res; //add the newly fetched row data into the results array
}
echo json_encode($results); //encode the array, and then echo the result so that it goes into the response for the JavaScript to read.

mysqli_free_result($result_set);
mysqli_close($connection);

?>
"use strict";

google.charts.load('current', { 'packages': ['line'] });

document.getElementById('get').addEventListener('click', getData);

function addRow(data) {
    let tBody=document.getElementById("sensorData");
    let row=tBody.insertRow(-1);

    let cell=row.insertCell(-1);
    let dateTextNode=document.createTextNode(data.date);
    cell.appendChild(dateTextNode);

    cell=row.insertCell(-1);
    let temperatureTextNode=document.createTextNode(data.temperature);
    cell.appendChild(temperatureTextNode);

    cell=row.insertCell(-1);
    let pressureTextNode=document.createTextNode(data.pressure);
    cell.appendChild(pressureTextNode);

    cell=row.insertCell(-1);
    let rpmTextNode=document.createTextNode(data.rpm);
    cell.appendChild(rpmTextNode);
}

async function getData() {

    let response = await fetch("http://localhost:8000/read1.php");
    let json = await response.json();

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'date');
    data.addColumn('number', 'temperature');
    data.addColumn('number', 'pressure');
    data.addColumn('number', 'rpm');

    //loop through the data and add a table row and a chart row for each row received from the server
    for (var i = 0; i < json.length; i++) {
      addRow(json[i]);
      data.addRow(Object.values(json[i]));
    }

    var options = {
        chart: {
            title: 'Sensor Data',
            subtitle: ''
        },
        width: 1045,
        height: 500
    };

    var chart = new google.charts.Line(document.getElementById('linechart_material'));
    chart.draw(data, google.charts.Line.convertOptions(options));
}
<!DOCTYPE html>
    <html>

    <head>
    <title>Sensor Data</title> 
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>

    <body>
       <header id="main-header">
        <div class="container">
          <h1><center>Sensor data</center></h1>
        </div>
       </header> 

        <section id="mainpic6">
        </section>

        <h1><center>Visualisation of sensor data --> last 100 records</center></h1>

        <div class="container">


        <section id="main4">

                <table>
              <thead>
                <tr>
                  <th>Date</th>
                  <th>Temperature</th>
                  <th>Pressure</th>
                  <th>RPM</th>
                </tr>
              </thead>
              <tbody id="sensorData">
                <tr>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                </tr>

                    <button id="get">GET</button>

              </tbody>
            </table>

        </section>

            <div></div>

            <aside id="sidebar2">

                <div id="linechart_material"></div>

            </aside>

        </div>





        <footer id="main-footer">
        <p>Copyright &copy; 2020 Arturas Website</p>
        </footer>

        <script src="script/script.js"></script>

    </body>

    </html>

Arthur亚瑟

The remaining issues with the PHP are: PHP 的其余问题是:

1) You're not using your loop to create an array of rows, and instead you're trying to encode the Mysqli result set. 1)您没有使用循环来创建行数组,而是尝试对 Mysqli 结果集进行编码。 That doesn't contain the row data directly, it has to be fetched (which is what the while loop is for).它不直接包含行数据,它必须被获取(这就是while循环的用途)。

2) You're still outputting HTML as well, which will confuse the JavaScript code when it tries to read your response (and assumes - as it should - that it can treat it all as JSON) 2)您仍在输出 HTML ,这会在 JavaScript 代码尝试读取您的响应时混淆(并假设 - 它应该 - 它可以将其全部视为 JSON)

3) You're not echoing the encoded JSON - in fact you're not doing anything with it at all. 3)您没有回显编码的 JSON - 实际上您根本没有对它做任何事情。

This should work better:这应该会更好:

$results = []; //new blank array ready for populating with row data

while($res = mysqli_fetch_array($result_set)) {
  $results[] = array(
    "date" => $res["date"],
    "temperature" => (int) $res["temperature"],
    "pressure" => (int) $res["pressure"],
    "rpm" => (int) $res["rpm"],
  ); //add the necessary fields from the newly fetched row data into the results array
}

echo json_encode($results); //encode the array, and then echo the result so that it goes into the response for the JavaScript to read.

Also I don't know where you found the JavaScript, but it seems to be overcomplicating things, or is expecting a much more complex result set from the server, and it doesn't entirely make sense anyway in some places - I don't think it would work properly even with the dataset it's anticipating.另外我不知道您在哪里找到 JavaScript,但它似乎过于复杂,或者期望服务器提供更复杂的结果集,而且在某些地方它并不完全有意义 - 我不认为即使使用它预期的数据集它也能正常工作。

Therefore please replace the getData function with:因此,请将 getData function 替换为:

async function getData() {

    let response = await fetch("http://localhost:8000/read.php");
    let json = await response.json();

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'date');
    data.addColumn('number', 'temperature');
    data.addColumn('number', 'pressure');
    data.addColumn('number', 'rpm');

    //loop through the data and add a table row and a chart row for each row received from the server
    for (var i = 0; i < json.length; i++) {
      addRow(json[i]);
      data.addRow(Object.values(json[i]));
    }

    var options = {
        chart: {
            title: 'Sensor Data',
            subtitle: ''
        },
        width: 1045,
        height: 500
    };

    var chart = new google.charts.Line(document.getElementById('linechart_material'));
    chart.draw(data, google.charts.Line.convertOptions(options));
}

Then replace the addRow function with this version:然后用这个版本替换addRow function:

function addRow(data) {
    let tBody=document.getElementById("sensorData");
    let row=tBody.insertRow(-1);

    let cell=row.insertCell(-1);
    let dateTextNode=document.createTextNode(data.date);
    cell.appendChild(dateTextNode);

    cell=row.insertCell(-1);
    let temperatureTextNode=document.createTextNode(data.temperature);
    cell.appendChild(temperatureTextNode);

    cell=row.insertCell(-1);
    let pressureTextNode=document.createTextNode(data.pressure);
    cell.appendChild(pressureTextNode);

    cell=row.insertCell(-1);
    let rpmTextNode=document.createTextNode(data.rpm);
    cell.appendChild(rpmTextNode);
}

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

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