PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Handling SQL Errors in PDO

Note: This article was originally published at Planet PHP on 19 April 6700.
Planet PHP

I love PHP's PDO (PHP Data Objects) extension; it gives a consistent, object-oriented interface to handling all kinds of relational database backends. One thing that annoys me is that the MySQL driver for PDO defaults to a silent error mode which can make SQL errors tricky to spot!

To give you an example, consider the query below (the correct tablename is country, so this SQL will fail):

$db = new PDO('mysql:host=localhost;dbname=sakila', 'user', 'pass'); A $sql = 'select * from countrt'; $stmt = $db-query($sql); A while(($row = $stmt-fetch()) != false) { echo $row['country'] . "\n"; }

The script will output an error because $stmt is not an object.

You have a few options here - you can check that you got an object back before you try to do anything with it, for example. Alternatively you can prepare() and then execute() the statement, which means that you'll have a statement object and if there are any errors, they'll be available. This gives code that looks something like:

$db = new PDO('mysql:host=localhost;dbname=sakila', 'user', 'pass'); A $sql = 'select * from countrt'; $stmt = $db-prepare($sql); $stmt-execute(); A if($stmt-errorCode() == 0

Truncated by Planet PHP, read more at the original (another 3022 bytes)