PHP
  Home arrow PHP arrow Page 2 - Handling MySQL Data Set Failures in PHP 5
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

Handling MySQL Data Set Failures in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 3
    2008-10-29


    Table of Contents:
  • Handling MySQL Data Set Failures in PHP 5
  • Intercepting MySQL-related exceptions with PHP 5
  • Triggering custom exceptions when processing MySQL data sets
  • Handling MySQL and result set exceptions with separated try-catch blocks

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Handling MySQL Data Set Failures in PHP 5 - Intercepting MySQL-related exceptions with PHP 5
    ( Page 2 of 4 )

    Before I start teaching you how to implement a custom exception system to process some errors that might arise when working with MySQL data sets, I'm going to show you the example developed in the previous tutorial of this series. In this way, it will be fresh in your mind when we start covering the new material.

    In simple terms, the example in question was aimed at demonstrating how to use a MySQL abstraction class to trigger, and eventually intercept, some MySQL-related exceptions. This process required defining a couple of sample classes, called "MySQL" and "Result" respectively, in addition to deriving a subclass from the built-in "Exception" class included with PHP 5.

    Below I listed the corresponding signatures for all of these classes, along with a short script that shows how to use them together. Take a look at the following code sample, please:


    // extend the built-in exception class to throw MySQL-related exceptions

    class MySQLException extends Exception{

    public function __construct($message,$code=0){

    // call parent of Exception class

    parent::__construct($message,$code);

    }

    public function showExceptionInfo(){

    return 'Catching MySQL exceptions...<br />Exception message: '.$this->getMessage().'<br />Source filename of exception: '.$this->getFile().'<br />Source line of exception: '.$this->getLine();

    }

    }


    // define 'MySQL' class

    class MySQL{

    private $conId;

    private $host;

    private $user;

    private $password;

    private $database;

    private $result;

    const OPTIONS=4;

    public function __construct($options=array()){

    if(count($options)!=self::OPTIONS){

    throw new MySQLException('Invalid number of connection parameters');

    }

    foreach($options as $parameter=>$value){

    if(!$value){

    throw new MySQLException('Invalid parameter '.$parameter);

    }

    $this->{$parameter}=$value;

    }

    $this->connectDB();

    }

    // connect to MySQL

    private function connectDB(){

    if(!$this->conId=mysql_connect($this->host,$this->user,$this->password)){

    throw new MySQLException('Error connecting to the server');

    }

    if(!mysql_select_db($this->database,$this->conId)){

    throw new MySQLException('Error selecting database');

    }

    }

    // run query

    public function query($query){

    if(!$this->result=mysql_query($query,$this->conId)){

    throw new MySQLException('Error performing query '.$query);

    }

    return new Result($this,$this->result);

    }

    }


    // define 'Result' class

    class Result {

    private $mysql;

    private $result;

    public function __construct($mysql,$result){

    $this->mysql=$mysql;

    $this->result=$result;

    }

    // fetch row

    public function fetchRow(){

    if(!$row=mysql_fetch_assoc($this->result)){

    return false;

    }

    return $row;

    }

    // count rows

    public function countRows(){

    if(!$rows=mysql_num_rows($this->result)){

    throw new Exception('Error counting rows');

    }

    return $rows;

    }

    // count affected rows

    public function countAffectedRows(){

    if(!$rows=mysql_affected_rows($this->mysql->conId)){

    throw new Exception('Error counting affected rows');

    }

    return $rows;

    }

    // get ID of last-inserted row

    public function getInsertID(){

    if(!$id=mysql_insert_id($this->mysql->conId)){

    throw new Exception('Error getting ID');

    }

    return $id;

     }

    // seek row

    public function seekRow($row=0){

    if(!is_int($row)||$row<0){

    throw new Exception('Invalid result set offset');

    }

    if(!mysql_data_seek($this->result,$row)){

    throw new Exception('Error seeking data');

    }

    }

    }


    try{

    // connect to MySQL

    $db=new MySQL(array('host'=>'host','user'=>'user','password'=>'password','database'=>'database'));

    // fetch data on some users

    $result=$db->query('SELECT * FROM users');

    // display data on some users

    while($row=$result->fetchRow()){

    echo 'First Name: '.$row['firstname'].' Last Name: '.$row['lastname'].' Email: '.$row['email'].'<br />';

    }

    // turn off MySQL (throws a MySQL exception)

     

    /* displays the following

    Catching MySQL exceptions...

    Exception message: Error connecting to the server

    Source filename of exception: path/to/file/exception_test.php

    Source line of exception: 36

    */

    }

    // catch MySQL exceptions here

    catch(MySQLException $e){

    echo $e->showExceptionInfo();

    exit();

    }

    // catch default exceptions here

    catch(Exception $e){

    echo 'Catching default exceptions...<br />';

    echo 'Exception message: '.$e->getMessage().'<br />';

    echo 'Source filename of exception: '.$e->getFile().'<br />';

    echo 'Source line of exception: '.$e->getLine();

    exit();

    }


    If you closely examine the above example, you'll definitely realize how simple it is to extend the functionality of the native exceptions mechanism provided by PHP 5. As you can see, in this case the previous "MySQL" class will throw only exceptions of type "MySQLException" if an error occurs when attempting to connect to the server,  select a specified database or run queries.

    Besides, it's worth mentioning that two different "try-catch" blocks are used in this specific case. The first one will intercept only MySQL-related exceptions, while the second block will catch generic ones. Quite simple to understand, isn't it?

    Well, provided that you now understand how the previous hands-on example functions, it's time to learn other useful things regarding the implementation of exception subclasses with PHP 5.

    You previously learned how to build a MySQL abstraction class that is capable of triggering some specific exceptions. So in the following section I'm going to show you how to modify the signature of the "Result" class shown above in such a way that it will be able to throw custom exceptions only when processing MySQL result sets.

    Sounds pretty interesting, right? However, to learn the full details of how this process will be performed, you'll have to click on the link below and keep reading.



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek