php-即使有错误,PDO错误代码也总是00000

我正在运行PHP 7.2.16

不确定启动时,即使有错误,PDO errorCode()或errorInfo()[0]现在总是显示00000

$pdo = new \PDO('MysqL:host=localhost;dbname=mydb','root','pwd');
$sth = $pdo->prepare('select now() and this is a bad sql where a - b from c');
$sth->execute();
$row = $sth->fetchAll();
$err = $sth->errorInfo();
echo $sth->errorCode();
print_r($row);
print_r($err);

结果如下:

00000Array
(
)
Array
(
    [0] => 00000
    [1] => 1064
    [2] => You have an error in your sql Syntax; check the manual that corresponds to your MariaDB server version for the right Syntax to use near 'a bad sql where a - b from c' at line 1
)

但是,我只是做了一个新测试,通过删除$sth-> fetchAll()或在此行之前获取错误,可以正确显示

Array
(
    [0] => 42000
    [1] => 1064
    [2] => You have an error in your sql Syntax; check the manual that corresponds to your MariaDB server version for the right Syntax to use near 'a bad sql where a - b from c' at line 1
)

OK-解决方案是:

get the error code immediately after execute() and before any fetch

最佳答案
我使用PHP 7.1.23测试了以下代码

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,true);
$sth = $pdo->prepare('select now() and this is a bad sql where a - b from c');
if ($sth === false) {
  echo "error on prepare()\n";
  print_r($pdo->errorInfo());
}
if ($sth->execute() === false) {
  echo "error on execute()\n";
  print_r($sth->errorInfo());
}

输出

error on execute()
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 'a bad sql where a - b from c' at line 1
)

然后,我测试了相同的代码,除非禁用了仿真的prepare:

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);

输出

error on 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 'a bad sql where a - b from c' at line 1
)

Fatal error: Uncaught Error: Call to a member function execute() on boolean

故事的道德启示:

>使用模拟的准备好的语句时,prepare()是空操作,并且错误会延迟到execute()为止.我建议禁用模拟的prepare,除非您使用的数据库不支持prepared语句(我不知道任何RDBMS产品的任何当前版本都不能执行真正的prepared语句).
>在prepare()上检查错误时,请使用$pdo-> errorInfo().
>在execute()上检查错误时,请使用$stmt-> errorInfo().

相关文章

昨天的考试过程中,有个考点的服务器蓝屏重启后发现Mysql启动不了(5.6.45 x32版本,使用innoDB),重装后...
整数类型 标准 SQL 中支持 INTEGER 和 SMALLINT 这两种类型,MySQL 数据库除了支持这两种类型以外,还扩...
一条 SQL 查询语句结构如下: SELECT DISTINCT <select_list> FROM <left_table&...
数据备份 1. 备份数据库 使用 mysqldump 命令可以将数据库中的数据备份成一个文本文件,表的结构和数据...
概述 在实际工作中,在关系数据库(MySQL、PostgreSQL)的单表数据量上亿后,往往会出现查询和分析变慢...
概述 触发器是 MySQL 的数据库对象之一,不需要程序调用或手工启动,而是由事件来触发、激活,从而实现...