Error Handling In PHP’s PDO

Author: No comments

With last weeks explanation on how to handle errors & exceptions in PHP5, it's time to advance in this area. Using PHP's PDO (PHP Data Object), you can create powerful database-driven applications. Portable, and more secure.

It allows you to channel all database-related tasks through a PDO interface, in order to communicate to your backend database. This gives you the ability to port your application to another database (MySQL, PostgreSQL, ...) by changing the PDO 's specified driver and create so called Prepared Statements for an extra layer of security.

Code containg a PDO-object could look similar to the one shown below.

It creates a simple connection to a MySQL host, using the login credentials provided at the top.

An important thing to note here, is that when the PDO-constructor throws an exception which isn't handled by your own code, PHP's built-in Exception Handler will kick in. This means a backtrace will be shown, leading up to the error message. In the constructor's case, this could very well mean your database's username & password. Obviously, we don't want that.

Using the previously discussed Exception handling, we can safely handle this.


Add Your Comment