我是使用 PDO 的新手,我发现由于查询语句中的错误导致的异常没有被捕获和正确显示。发生这种情况时的页面输出通常如下所示:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: ...
我使用以下函数进行 PDO 查询:
/**************************************************************************************************************
* 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();
}
}
知道为什么没有捕获异常吗?
编辑:这就是我创建 PDO 对象的方式:
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;
}