简体   繁体   中英

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. So basically my html has to call script.js file which is using read.php as API to extract the data out my database.

My html file is ok i think. But im so stuck with.js and.php files.

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.

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:

1) You're not using your loop to create an array of rows, and instead you're trying to encode the Mysqli result set. That doesn't contain the row data directly, it has to be fetched (which is what the while loop is for).

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)

3) You're not echoing the encoded JSON - in fact you're not doing anything with it at all.

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.

Therefore please replace the getData function with:

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:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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