IDIOT DEVELOPER

Exceptions in PDO (PHP Data Object)
Exceptions in PDO (PHP Data Object)

In some of the previous posts, we have learn about the PDO (PHP Data Object). In this article we are going to deal with Exceptions in PDO. It is always necessary to wrap a PDO statement in a try/catch block. As there can be chance that any error may occur, so to handle those errors we use PDO Exceptions. We can force PDO into one of the three error modes by setting the error mode attribute on your newly created database handler.

 


$DB->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
$DB->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$DB->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

 

Here:

1. $DB is the the PDO Object, that is used for handling the database.

2. setAttribute is the function the PDO class that is used to set attribute on the database handler.

3. PDO::ATTR_ERRMODE is the error reporting attribute.

 

No matter what error mode you set, an error connecting will always produce an exception, and creating a connection should always be contained in a try/catch block.

 

There are three kinds of error attribute value:

1. PDO::ERRORMODE_SILENT

2. PDO::ERRORMODE_WARNING

3. PDO::ERRORMODE_EXCEPTION

 

PDO::ERRORMODE_SILENT

This is the default error mode. If you leave it in this mode, you’ll have to check for errors in the way you’re probably used to if you used the mysql or mysqli extensions. The other two methods are more ideal for DRY programming.

 

PDO::ERRORMODE_WARNING

This mode will issue a standard PHP warning, and allow the program to continue execution. It’s useful for debugging.

 

PDO::ERRORMODE_EXCEPTION

This is the mode you should want in most situations. It fires an exception, allowing you to handle errors gracefully and hide data that might help someone exploit your system. Here’s an example of taking advantage of exceptions:

 

 


try {
  $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
  $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
 
  // Type SELECTE instead of SELECT 
  $DBH->prepare('SELECTE name FROM people');
}
catch(PDOException $e) {
    echo "Exception: " + $e;
}

 

There’s an intentional error in the select statement; this will cause an exception. The exception details will be printed on the screen.

Leave a Reply

Your email address will not be published. Required fields are marked *