Best way to handle PDO query exceptions
I have a basic question on the best practices way to use try/ catch blocks with PDO queries in php. Say I have a query:
$sql = "SELECT id FROM table WHERE name = ?";
$sth = $dbh->prepare($sql);
$sth->bindValue(1, $param);
$sth->execute();
$result = $sub_sth->fetchColumn();
What is the best practice method for encapsulating this in a try block and catching an exception in either the sql syntax or e开发者_如何学Goxecution?
N.B. the PDO connection itself ($dbh) already has exception handling.
It is usually helpful to make your error handling as atomic as possible. Encapsulate each of the statements that may throw an exception in a separate try/catch block.
In this case, the statements that may throw exceptions are:
$sth = $dbh->prepare($sql);
and
$sth->execute();
This granularity allows you to troubleshoot problems with precision, as opposed to large try/catch blocks which allow you only to find the section of code that caused a problem.
See Ralph Shindler's article for an in-depth treatment of the subject.
Depending on the configuration PDO uses emulated prepared statements. Hence the ->prepare
call itself will not trigger an exception. That's why you should wrap both prepare
and ->execute
in the same try{}
block.
In my experience with real prepared queries it's uncommon to see exceptions only on the ->execute
call anyway. It's most typically the SQL query that's wrong. However that is a development problem, not a runtime issue, so catching exceptions for the prepare seems less logical.
Anyway, my advise would be to wrap both unless you can really come up with a way to recover in two different ways from the problem (which IMHO is unlikely for the SQL ->prepare
and syntax errors.)
精彩评论