If query return no results using PDO

I want to display “no records found” if my query returns no results. Heres my code

  <table class="table table-striped">
  <tr>
  <th width="75">Date</th>
  <th width="200">Provider</th>
  <th width="200">Author</th>
  <th>Details...</th>
  </tr>
<?php
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);     

try {
$stmt = $dbh->prepare('SELECT ...');
$stmt->execute(array(
':p_id' => $_GET['p_id'] 
));  

	while($row = $stmt->fetch()) {
			echo "<tr>";
			echo "<td>".date( 'm/d/y', strtotime($row['r_date']))."</td>";
			echo "<td>".$row['p_name']."</td>";
			echo "<td>".$row['m_name']."</td>";
			echo "<td>".$row['excerpt'].". . .&nbsp;&nbsp;<a href='review_detail.php?id=".$row['id']."'><span class='more'>[more]</span></a></td>";
			echo "</tr>\n";
	}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
</table>

Im thinking I got to put this before the while loop

if (is_array($fetch))  {

while() {
...
}

} else {
echo '<tr><td colspan="4" align="center">no records found!!</td></tr>';

}

You should always be putting your while loops through an else if statement. If you don’t, your loops will be infinite.

You need to check to see if the data exists first using rowCount. Within the rowCount, you can then use the while loop.

So something like this

$stmt = $dbh->prepare('SELECT ...');
$stmt->execute(array(
':p_id' => $_GET['p_id']
));
if($stmt->rowCount()) {
      // While loop here
} else {
      // Return your "No record found" error
}

As you have PDO::ERRMODE_EXCEPTION set in your connection string you then catch the exception in a try/catch statement as well:

try {

if($stmt->rowCount()) {
      // While loop here
} else {
      // Return your "No record found" error
     return;
}

} catch (PDOException $e) {
    echo $e->getMessage
}

thanks

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.