Error Handling In PHP’s PDO

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, January 23, 2009

Follow me on Twitter as @mattiasgeniar

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());
	}
?>


Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.