我使用PHP使用数据表来显示数据库中的记录。

请参阅下面的代码;

<table class="table datatable-basic">
  <thead>
    <tr>
      <th> ID </th>
      <th> Name</th>
      <th>Address </th>
      <th class="text-center">Actions</th>
    </tr>
  </thead>
  <tbody>

  <?
  $result9023=mysql_query("SELECT * FROM hr_locations")or die('ERROR 315' );
  $num_rows = mysql_num_rows($result9023);

  for ($i = 1; $i <= mysql_num_rows($result9023); $i++) {
    $row = mysql_fetch_array($result9023);
    $location_id = $row ['id'];
    $name = $row ['location'];
    $address = $row ['address'];

    echo "         <tr>
        <td>$location_id</td>
        <td>$name</td>
        <td>$address</td>
        <td class='text-center'>Edit</td>
      </tr>
    "; } ?>
  </tbody>
</table>


该表显示正确,并已填充数据,但是在页面加载时出现以下错误。

php - 数据表错误-LMLPHP

我看过https://datatables.net/tn/4,但这没有多大意义?

最佳答案

由于大多数MySQL数组均以0开头,因此请执行以下操作:

for ($i = 0; $i < $num_rows; $i++) {


设置$i = 0然后声明$i必须少于行数(如果有4,则将得到0、1、2、3(4行,已正确索引)。您已经为计数设置的变量。



实际上,您可能对代码做了太多的事情。不用使用不必要的for循环,只需使用一会儿:

while($row = mysql_fetch_array($result9023)){
    $location_id = $row ['id'];
    $name = $row ['location'];
    $address = $row ['address'];

    echo "         <tr>
        <td>$location_id</td>
        <td>$name</td>
        <td>$address</td>
        <td class='text-center'>Edit</td>
      </tr>
    "; } ?>


这样,您可以确保捕获查询返回的每一行,而不会像尝试将for循环与mysql_fetch_array()一起使用时那样重复或跳过行。

关于php - 数据表错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41019298/

10-16 20:35
查看更多