Home Tutorials Exception handling

Exception handling

  previous next
February 09, 2009 by Victor    

Another point I‘d like to bring to your attention is exception handling. Our database queries will either be divine or they will fall into the shadows. If your code is not protected it will fail miserably, otherwise it will have a glorious failure, great difference.

OK, we have to check for possible sources of error, for example, say the table you are trying to query does not exist or your query for some reason returns an empty record set. Shirt happens; we have to take care of such things in our code. The following example simply tests for an empty record set:

<?php
  $db =& JFactory::getDBO();
  $sql = 'SELECT id,title from #__content where id > 1000';
  $db->setQuery($sql);
  $rows = $db->loadObjectList();
 
  if (empty($rows)) 
  {
      print "<p>There are no articles to display</p>";
  }
  else
  {
      print "<p>There are some stuff in here</p>";
  }    
?>

The next one prints database errors using methods from the JDatabase class.

<?php
  $db =& JFactory::getDBO();
  $sql = 'SELECT idtitle form #__content';
  $db->setQuery($sql);
  $rows = $db->loadObjectList();
 
  print "<p>Error:".$db->getErrorNum()."-".$db->getErrorMsg()."</p>"; 
?>

Some people use $db->stderr(), not much of a difference really, possibly an older one?

Combining the above, we could write the following, to look better.

<?php
  $db =& JFactory::getDBO();
  $sql = 'SELECT id,title from #__content where id > 40';
  $db->setQuery($sql);
  $rows = $db->loadObjectList();
 
  if ($db->getErrorNum()) 
  {
      print "<p>Database Error</p>";
      print "<p>Error:".$db->getErrorNum()."-".$db->getErrorMsg()."</p>";
  }
  else
  {
      if (empty($rows))
      {
          print "<p>There are no articles to display</p>";
      }
      else
      {
          foreach ($rows as $row)
          {
              echo "<p>The article id of '$row->title' is $row->id</p>\n";
          }
      }
  }
?>

Add comment


Security code
Refresh