将MySQL查询循环转换为PHP数组(表)

时间:2015-05-13 09:14:02

标签: php html mysql arrays

我有一个查看数据库的系统,创建一个指定大小的表,然后用full或empty填充单元格,具体取决于数据库中是否存在该特定位置的数据。

目前它通过对每个单元格执行SQL查询然后填充来工作,但是我在数据库中有30,000多条记录,即使使用LIMIT 1,它仍然需要大约5秒才能加载表格。

我想知道是否将整个内容转储到PHP数组然后以这种方式查询会更好,但不能找到最好的排序方式,欢迎任何提示。

当前(工作)代码:

echo <<<EOD
<table class="racktable"><tr>
<td colspan ="$colspan">Rack Details </td>
</tr>
<tr>
<td colspan ="$colspan"><center><a href="edit-rack.php?rack=$rackID">Edit Rack</a> / <a href="edit.php?query=emptyr&rack=$rackno&location=$location&user=$user">Empty Rack</a> / <a href="edit.php?query=delrack&rack=$rackID&user=$user&loc=$location">Delete Rack</a></center> </td>
</tr>
EOD;
//Loop through rows, creating a <tr> for each in the table
  for ($row1 = 1; $row1 <= $rows; $row1++) {
    echo <<<EOD
    <tr><td><a name="$row1"></a>$row1</td>
EOD;
    //Loop through columns creating <td> within <tr>
    for ($col1 = 1; $col1 <= $columns; $col1++) {
      $sql2 = "SELECT ID, sample, rack, srow, col, location FROM samples WHERE srow = $row1 and col = $col1 and location = '$location' and rack = '$rack' LIMIT 1";
      if (!$result2 = $db->query($sql2)) {
        die('There was an error running the query [' . $db->error . ']');
      }
      $row3 = $result2->num_rows;
      //If location is empty, colout green
      if ($row3 == 0) {
        echo "<td style=\"background-color: #A3CD81\">" . $col1 . "</td>";
      }
      else {
          //Location is not empty, colour red and link to sample
        while ($row2 = $result2->fetch_assoc()) {
          $columns1 = $row2['col'];
          $ID = $row2['ID'];
          $tooltip = $row2['sample'];
          $queryStr = $_SERVER['QUERY_STRING'];
          $spath = $_SERVER['PHP_SELF'] . "?" . $queryStr . "&sample=" . $ID;
          echo <<<EOD
        <td style="background-color: #FF0000" title="$tooltip"><a href="$spath">$col1 <img src="icon.png" style="border: 0" alt=""></a></td>
EOD;

        }
      }
    }
    echo "</tr>";
  }
  echo "</table>";

2 个答案:

答案 0 :(得分:0)

您需要一个索引类似于

的数组
SELECT ID, sample, rack, srow, col, location
FROM samples
WHERE srow = $row1 and col = $col1 and location = '$location' and rack = '$rack'
LIMIT 1";

你的数组看起来像:

$samples = array(
  "$row1:$col1:$location:$rack" => array( 'id' => $id, 'sample' => $sample
)

或者你可以使用一些哈希数组,如:

$samples = array(
  md5( "$row1:$col1:$location:$rack" ) => array( 'id' => $id, 'sample' => $sample
)

插入所有值一次 - 而不是像

那样
$val = $samples["$row1:$col1:$location:$rack"];
// or from hash array
$val = $samples[md5( "$row1:$col1:$location:$rack" )];

答案 1 :(得分:0)

您可以使用以下代码将数据库中的所有数据直接转换为php数组:

while(($PHPToPHP[] = mysql_fetch_assoc($SqlResult )) || array_pop($dataToPHP));

可能适用于您的代码:

while(($dataToPHP[] = $result2->fetch_assoc()) || array_pop($dataToPHP))

要查看它的用途print_r($dataToPHP)

要管理错误die('There was an error running the query [' . $db->error . ']');if ($row3 == 0) { echo "<td style=\"background-color: #A3CD81\">" . $col1 . "</td>";}进行着色,您需要进行一些测试才能正确管理。