Error Handling In PHP’s PDO

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.


The Social Box

You can sign up for more updates via Twitter or Facebook below. On Twitter, I regularly talk about technology or tweet about interesting stories. Topics that don't necessarily make it to this blog. Facebook contains a steady update of blogposts and some more lightweight stories.

The @mattiasrss account has an automated RSS feed of all blogposts that get published.

Write a Comment

Do you care about the markup if your comment? You can use the following HTML tags:

<code>command</code>: command highlighting
<pre>text</pre>: pre-formatted code, can be multi-line (black background, white letters)

example <pre> tag
<blockquote>text</blockquote> quoted text
quoted example

None of this is needed of course, it's all optional!