Nat*_*ate 3 php error-handling pdo
每隔一段时间我就会收到一个错误,如下面的PDO错误:
错误!:SQLSTATE [HY093]:参数号无效:未定义参数
有没有办法得到更具体的错误,如行号,文件名,缺少的参数等,而不是模糊的消息?
首先,确保将PDO设置为在出错时抛出异常:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Run Code Online (Sandbox Code Playgroud)
现在,确保每个PDO操作/操作集都包含一个try/ catchblock,如下所示:
try {
$stmt = $pdo->prepare("SELECT * FROM Whatever");
// ...yada yada yada, your PDO code goes here
} catch (PDOException $e) {
// This will echo the error message along with the file/line no on which the
// exception was thrown. You could e.g. log the string to a file instead.
echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine();
}
Run Code Online (Sandbox Code Playgroud)
所有异常都从基Exception类扩展,因此继承了它的方法以及它带来的有关错误的信息.
作为旁注,如果将PDO与MySQL一起使用,请确保禁用模拟的预准备语句.有关如何执行此操作以及为何需要的详细信息,请参阅此处.