【发布时间】:2021-04-21 02:24:56
【问题描述】:
我正在尝试每分钟将 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>";
}
}
}
?>
【问题讨论】:
-
你应该打开一个数据库连接并重新使用同一个连接,重新连接是一个相对昂贵的过程。
-
尝试在单个查询中获取所有设备数据:
"SELECT temperature, preassure, info_time FROM test where device_id IN (1,2,3,4,5,6,7,8,9,10)" -
奈杰尔的建议是有效的,虽然它不应该造成这么大的滞后,我会寻找其他问题。在您的脚本中添加一些时间测量以确定哪个部分最有问题。临时增加执行时间以使调试更容易。