Checking for No Results

It is important to check for results before attempting to display them. This can be accomplished by fetching the first row of the result set and checking for a value.

<?php
  require_once "db.php";
  $sql = "SELECT * FROM movies";
  $result = $db->query($sql);
  $movie = $result->fetch();
?>

<? if (!$movie) : >
  <em>No results</em>
<?php endif; ?>

Of course, if there are results that first row will need to be included. This can be accomplished by switch to a do while loop.

<?php
  require_once "db.php";
  $sql = "SELECT * FROM movies";
  $result = $db->query($sql);
  $movie = $result->fetch();
?>

<? if (!$movie) : ?>
  <em>No results</em>
<?php else : ?>
  <ul>
    <?php do { ?>
      <li><?php echo $movie['movie_title']; ?></li>
    <?php } while ($movie = $result->fetch()); ?>
  </ul>
<?php endif; ?>