我必须从我的数据库中获取数据并将其显示在 data.html + google 图表中的表格中。所以基本上我的 html 必须调用 script.js 文件,它使用 read.php 作为 API 来从我的数据库中提取数据。
我认为我的 html 文件没问题。但我非常坚持使用 .js 和 .php 文件。
我需要帮助如何将数据从数据库存储到 .php 文件,然后使用 .js 文件中的数据在我的 html 表中添加行。
请大家帮忙。
<?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');
}
BIG阳