Getting Error Messages

When there is an error in the SQL query, it is not easy to find the problem using convention PHP methods. That is because the error occurs on the MySQL server and that error not relayed to PHP by default. Fortunately, there is a way to get the error information.

The errorInfo() method returns an array containing the error information about the last operation performed by the database. There are three elements or parts of the errorInfo:

  • SQLSTATE error code
  • Driver-specific error code
  • Driver-specific error message

This last part, which will be in index 2, is the one we are most interested in, because it contains a human-readable explanation of the error.

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

  echo $errorInfo[2]; // no such table: movis

If there was no error in the SQL then the third item in the errorInfo array would be empty. We can use this fact to create a error management system which will check for an SQL error before proceeding.

<?php
  require_once "db.php";
  $sql = "SELECT * FROM movies";
  $result = $db->query($sql);
  $error = $db->errorInfo()[2];
?>

<?php if (!$error) : ?>
  <?php $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; ?>
<?php else : ?>
  <em><?php echo $error ?></em>
<?php endif; ?>