我有代码:
$stmt = $db->prepare(" bla bla ");
$stmt->execute();
print_r($db->errorInfo());
返回:Array ( [0] => 00000 [1] => [2] => )
为什么不返回错误信息?
以下正确报告错误:
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
if (($stmt = $dbh->prepare(" bla bla ")) === false) {
print_r($dbh->errorInfo());
}
if ($stmt->execute() === false) {
print_r($stmt->errorInfo());
}
注意在上文中,针对$dbh
报告了在prepare()
期间导致的解析错误。然而,即使prepare()
成功,execute()
也可能导致错误,但该错误是针对$stmt
报告的。
在上面的测试中,我在prepare()
:之后立即得到了错误报告
Array
(
[0] => 42000
[1] => 1064
[2] => You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right
syntax to use near 'bla bla' at line 1
)
但如果使用模拟准备,则此行为会发生变化
当您启用该属性时,prepare()
实际上是一个no-op。它只是将查询字符串保存在$stmt中,然后语句的实际准备将被延迟,直到您调用execute()
。因此,无论是在准备时还是在执行时,都会针对$stmt
报告错误(如果有)。
我测试更改错误报告行如下:
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
// prepare won't report SQL errors, it's virtually a no-op.
if (($stmt = $dbh->prepare(" bla bla ")) === false) {
print_r($dbh->errorInfo());
}
// execute will report errors of parsing or execution.
if ($stmt->execute() === false) {
print_r($stmt->errorInfo());
}
在这种情况下,prepare()
没有报告错误,但我在execute()
得到了与上述相同的错误。同样,您必须检查$stmt
才能得到execute()
之后的错误。
SQLSTATE 00000表示"成功"。根据PHP文档:
如果未设置SQLSTATE错误代码,或者没有驱动程序特定的错误,则元素0后面的元素将设置为NULL。