数据 table 错误

Data table error

我正在使用数据table 显示数据库中的记录,使用 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>

table 显示正确,数据填充正确,但是当页面加载时出现以下错误。

我看过 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:

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() 时那样重复或跳过行。