Home arrow PHP arrow Page 2 - Handling MySQL Data Set Failures in PHP 5

Intercepting MySQL-related exceptions with PHP 5 - PHP

If you’re a PHP developer who wants to learn the basics of implementing customized exceptions in PHP 5, then look no further, because you’ve come to the right place. This is the third part of a four-part series entitled “Subclassing exceptions in PHP 5.” It teaches you how to extend the native exception mechanism bundled with PHP 5 by using inheritance, and complements the corresponding theory with copious, illustrative hands-on examples.

TABLE OF CONTENTS:
  1. Handling MySQL Data Set Failures in PHP 5
  2. Intercepting MySQL-related exceptions with PHP 5
  3. Triggering custom exceptions when processing MySQL data sets
  4. Handling MySQL and result set exceptions with separated try-catch blocks
By: Alejandro Gervasio
Rating: starstarstarstarstar / 4
October 29, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: