I really can't figure out what I'm doing wrong here. I'm doing a query to check whether there are records in a DB table called 'newCards'.
With $count I check how many results it's returning: it shows me '1'. But the while loop isn't returning ANY thing. The only things I'm seeing are the <th>'s at the top of the table, but no table records are present, while $count is giving '1' as a result. Which is true, cause there is actually 1 record present in DB.
How can I fix this?
<?php
$query = $db->prepare("SELECT * FROM `newCards` WHERE `company` = :companyID");
$query->bindParam(":companyID", $enterprise['id'], PDO::PARAM_INT);
$query->execute();
$count = $query->rowCount();
echo $count;
if(empty($query->fetch())){
echo "Geen gevonden";
} else {
?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
while($result = $query->fetch()){
?>
<tr>
<td><?php echo $result['id']; ?></td>
<td>2</td>
<td>3</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
fetch()returns FALSE not only when there are no records found, but also when the querying of the db fails, from different reasons. And you can not differentiate between the two situations. This is a bug in PDO. So, I'd recommend you to usefetchAll()instead. It returns an empty array when no records are found, or FALSE on failure. Both situations can be handled correspondingly. Also, don't mix data access functions within HTML. Fetch all data in arrays, in the upper php code. Work with that arrays when you're building your HTML parts.fetchAll()is a good approach - but it's seemingly not a bug that it returns false with an empty resultset. Someone reported it as a bug a good while back and got the issue closed with "working as intended"...