Error Handling In PHP’s PDO

Mattias Geniar, Friday, January 23, 2009 - last modified: Sunday, August 2, 2015

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.

getMessage());
	}
?>

Hi! My name is Mattias Geniar. I'm a Support Manager at Nucleus Hosting in Belgium, a general web geek, public speaker and podcaster. If you're interested in keeping up with me, have a look at my podcast and weekly newsletter below. For more updates, follow me on Twitter as @mattiasgeniar.

SysCast podcast

In the SysCast podcast I talk about Linux & open source projects, interview sysadmins or developers and discuss web-related technologies. A show by and for geeks!

cron.weekly newsletter

A weekly newsletter - delivered every Sunday - for Linux sysadmins and open source users. It helps keeps you informed about open source projects, Linux guides & tutorials and the latest news.

Share this post

Did you like this post? Will you help me share it on social media? Thanks!

Leave a Reply

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