Reputation: 525
Why my while loop not working, I also have a while loop on the other PHP page, but there's only one page that doesn't work with PHP's while loop. But it does not contain any errors. Here's my code:
$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>
';
}
Upvotes: 0
Views: 1822
Reputation: 94682
You were reading your first result row and incorrectly using that as a count of resulted rows, then ignoring its content.
$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>
';
}
}
Upvotes: 2
Reputation: 1
$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>";
}
Upvotes: 0