首页 > 解决方案 > 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>";

      }
    }
}

?>

在此处输入图像描述

标签: phphtmlmysql

解决方案


避免在循环内运行查询。我以更好的方式更改了代码。它将在不到一秒的时间内获取结果。


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>";

    }
}

推荐阅读