php - php需要很长时间才能从数据库中加载数据
问题描述
我正在尝试每分钟将 10 个设备(温度和压力传感器)的数据加载到网页中,并每分钟重新加载页面(这些设备每分钟将数据发送到数据库)。但问题是,有时 PHP 运行时间过长。我经常收到 PHP 超时错误。是代码的问题还是可能是什么原因?(这些设备在 HTTP post 方法的帮助下发送数据)。
<?php
function getData($device_id)
{
include 'test_db_info.php';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT temperature, preassure, info_time FROM test where device_id = '$device_id'";
$result = $conn->query($sql);
$conn->close();
return $result;
}
$deviceID=array(1,2,3,4,5,6,7,8,9,10);
foreach ($deviceID as $id)
{
$rows_data= getData($id);
// if there is data, disyplay the data
if (!empty($rows_data))
{
foreach ($rows_data as $row)
{
echo '<table class= "mainTableClass"; >';
echo '<tr><th>Device</th>'; // first row - device
echo '<td >' . $id. '</td></tr>';
echo '<tr><th>Temp</th>'; // second row - temperature
echo '<td >' . $row['temperature']. '</td></tr>';
echo '<tr><th>Preassure</th>'; //third row - Preassure
echo '<td >' . $row['preassure']. '</td></tr>';
echo '<tr><th>Time</th>'; // fourth row - time
echo '<td >' . $row['info_time']. '</td></tr>';
echo "</table>";
}
}
}
?>
解决方案
避免在循环内运行查询。我以更好的方式更改了代码。它将在不到一秒的时间内获取结果。
include 'test_db_info.php';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$deviceID=array(1,2,3,4,5,6,7,8,9,10);
$devices_arr = implode("','",$deviceID);
$query = "SELECT device_id, temperature, preassure, info_time FROM test where device_id IN ('".$devices_arr."')";
$data=mysqli_query($conn,$query);
$devices = array();
while($row=mysqli_fetch_array($data)){
$devices[$row['device_id']] = $row;
}
foreach ($deviceID as $id){
if(isset($devices[$id])){
$row = $devices[$id];
echo '<table class= "mainTableClass"; >';
echo '<tr><th>Device</th>'; // first row - device
echo '<td >' . $id. '</td></tr>';
echo '<tr><th>Temp</th>'; // second row - temperature
echo '<td >' . $row['temperature']. '</td></tr>';
echo '<tr><th>Preassure</th>'; //third row - Preassure
echo '<td >' . $row['preassure']. '</td></tr>';
echo '<tr><th>Time</th>'; // fourth row - time
echo '<td >' . $row['info_time']. '</td></tr>';
echo "</table>";
}
}
推荐阅读
- swiftui - 有没有办法在 SwiftUI 中创建 WKExtendedRuntimeSession 的新会话?
- youtube - YouTube iFrame 播放器:此视频被限制在此域上观看
- java - 了解 JPMS 模块的错误
- mysql - 来自两个表的双重联接
- bash - 得到一个?和一个 [✘?] 而不仅仅是 zsh 上的分支图标和分支名称
- python - super() 最多接受 2 个参数(给定 8 个)
- asp.net - 使用关键字退出for循环
- rust - 使用 Rust 在 GTK GUI 上渲染小的 LaTeX 片段
- angular - @types/lodash/common/array.d.ts(483,22): 错误 TS1005: ';'
- swift - 创建一个 if 语句,其中一次只有一个按钮可以有边框