PDO errorinfo不返回信息

OTA*_*TAR 2 php pdo

我有代码:

$stmt = $db->prepare(" bla bla ");
$stmt->execute();
print_r($db->errorInfo());
Run Code Online (Sandbox Code Playgroud)

返回: Array ( [0] => 00000 [1] => [2] => )

为什么不返回错误信息?

Bil*_*win 6

以下正确报告该错误:

$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());
}
Run Code Online (Sandbox Code Playgroud)

请注意,上述内容prepare()是针对中报告的解析错误$dbh。即使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
)
Run Code Online (Sandbox Code Playgroud)

但是,如果您使用模拟的准备,则此行为会更改。

当您启用该属性时,prepare()实际上是无操作。它只是将查询字符串保存在$ 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());
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,没有报告错误prepare(),但我在上遇到了与上面相同的错误execute()。同样,您必须检查$stmt后得到错误execute()