PHP虽然循环不工作但没有错误

时间:2018-05-12 14:01:35

标签: php loops mysqli while-loop

为什么我的while循环不起作用,我在另一个PHP页面上也有一个while循环,但是只有一个页面在循环时不能与PHP一起工作。但它不包含任何错误。这是我的代码:

$sqlquery = "SELECT * FROM tbl_accredited";
$result = $con->query($sqlquery);
$num = mysqli_fetch_array($result);
if($num <= 0){
    echo "<h2>No records found.</h2>";
}
$x=0;
while($row = mysqli_fetch_assoc($result)){
    $x++;
    echo '
            <tr>
                <td>'.$x.'</td>
                <td>'.$row['permitno'].'</td>
                <td>'.$row['boarding_optr'].'</td>
                <td>'.$row['boarding_addr'].'</td>
                <td>'.$row['orno'].'</td>
                <td>'.$row['boarding_name'].'</td>
            </tr>
    ';
}

2 个答案:

答案 0 :(得分:1)

您正在阅读第一个结果行,并错误地将其用作结果行的计数,然后忽略其结果。

$sqlquery = "SELECT * FROM tbl_accredited";
$result = $con->query($sqlquery);
$num = mysqli_fetch_array($result);
// this reads the first row of your result set and then of course gets lost
//$num = mysqli_fetch_array($result);

// use mysqli_num_rows instead
if(mysqli_num_rows($result) <= 0){
      echo "<h2>No records found.</h2>";
} else {
    $x=0;

    // now this will get the first row, which you must have been missing before
    while($row = mysqli_fetch_assoc($result)){
         $x++;
         echo '
                <tr>
                    <td>'.$x.'</td>
                    <td>'.$row['permitno'].'</td>
                    <td>'.$row['boarding_optr'].'</td>
                    <td>'.$row['boarding_addr'].'</td>
                    <td>'.$row['orno'].'</td>
                    <td>'.$row['boarding_name'].'</td>
                </tr>
          ';
    }
}

答案 1 :(得分:0)

$sqlquery = "SELECT * FROM tbl_accredited";
$result = $con->query($sqlquery);
$x=0;

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    $x++;
    echo '
      <tr>
      <td>'.$x.'</td>
      <td>'.$row['permitno'].'</td>
      <td>'.$row['boarding_optr'].'</td>
      <td>'.$row['boarding_addr'].'</td>
      <td>'.$row['orno'].'</td>
      <td>'.$row['boarding_name'].'</td>
      </tr>
    ';
  }
} 
else {
  echo "<h2>No records found.</h2>";
}