php - PDO 错误代码始终为 00000,即使出现错误

标签 php mysql pdo

我正在运行 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
)

好的 - 解决方案是:

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
)

然后我测试了相同的代码,除了在禁用模拟准备之后:

$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()。我建议禁用模拟准备,除非您使用的数据库不支持准备语句(我不知道任何 RDBMS 产品的当前版本不能执行真正的准备语句)。

  • 检查 prepare() 的错误时,使用 $pdo->errorInfo()

  • 检查 execute() 的错误时,使用 $stmt->errorInfo()

关于php - PDO 错误代码始终为 00000,即使出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55387802/

相关文章:

php - 选择数据并在所选记录中查找重复值的sql查询

php - Doctrine 2 和 Propel 1.6 的弱点和力量

php - 在不使用 Try and Catch 的情况下获取 PDO 错误

mysql - 在mysql中连接任意数量的字符串行(分层查询)

sql - 如何在开始时将相同的输入传递给所有 sql 文件一次?

php - 将 HTML 表单提交插入 MySQL 表(使用 PDO)

Laravel: SQLSTATE[28000] [1045] 用户 'homestead' @'localhost' 拒绝访问

php - 带有 PDO 下拉列表的 undefined variable

php - IIS - 提供带或不带尾部斜杠的无扩展名 PHP 文件

mysql - MySql 中的复合索引可以双向工作吗?