Dave Teu Dave Teu - 3 months ago 9x
SQL Question

Is there a need to test execute() result in PDO?

I usually use the following statement for pdo MySQL queries

$query = $db->prepare('MySQL statement');
$result = $query->execute(array())

Then use $query->fetch or fetchcolumn (to check Count(*)) to fetch data.

My question is - is there a need to test whether $result is true or not? In a productive environment if MySQL is down error will exist when we declare new PDO.

Under what circumstances do I need to test whether execute is true or false?


It depends on PDO::ATTR_ERRMODE, as explained in the Errors and error handling chapter.

If you configure PDO to throw exceptions (PDO::ERRMODE_EXCEPTION) then no, PDO will automatically throw an exception on error.

In any other case (use the default PDO connection options or explicitly set PDO::ERRMODE_SILENT or PDO::ERRMODE_WARNING) then yes, you need to verify manually the success of each individual operation.

It isn't useful that PDO::ERRMODE_EXCEPTION is not the default but, you know, PHP has a history of hiding helpful error messages for some misguided user-friendliness.