I’m new to using PDO and I’m finding that exceptions due to errors in the query statements are not being caught and displayed properly. The page output when this happens typically looks like:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: ...
I make PDO queries using the following function:
/**************************************************************************************************************
* Function: makeQuery *
* Desc: Makes a PDO query. *
* Pre conditions: The statement/query and an array of named parameters (may be empty) must be passed. *
* Post conditions: The PDO query is executed. Exceptions are caught, displayed, and page execution stopped. *
**************************************************************************************************************/
function makeQuery($stmt, $array, $errMsg = '')
{
try
{
$stmt->execute($array);
}
catch (PDOException $e)
{
print $errMsg != ''?$errMsg:"Error!: " . $e->getMessage() . "<br/>";
die();
}
}
Any idea why the exceptions are not being caught?
EDIT: This is how I create PDO objects:
function createPDO()
{
// MySQL connection details
$dbhost = '';
$dbuser = '';
$dbpass = '';
$dbname = '';
try
{
$db = new PDO("mysql:$dbhost=localhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch (PDOException $e)
{
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
return $db;
}
Are you sure every query is running through that function? Might look through your code to be 100% certain.
Another option is to define a global exception handler then just ask the thrown exception which line & file it came from:
http://php.net/manual/en/function.set-exception-handler.php
EDIT:
After some dialog w/ OP I’m now certain that the call to PDOStatement::prepare is where the Exception is being thrown, hence I’m recommending yet another wrapper function to the library: