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

前端之家收集整理的这篇文章主要介绍了php-即使有错误,PDO错误代码也总是00000 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在运行PHP 7.2.16

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

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

结果如下:

  1. 00000Array
  2. (
  3. )
  4. Array
  5. (
  6. [0] => 00000
  7. [1] => 1064
  8. [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
  9. )

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

  1. Array
  2. (
  3. [0] => 42000
  4. [1] => 1064
  5. [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
  6. )

OK-解决方案是:

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

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

  1. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,true);
  2. $sth = $pdo->prepare('select now() and this is a bad sql where a - b from c');
  3. if ($sth === false) {
  4. echo "error on prepare()\n";
  5. print_r($pdo->errorInfo());
  6. }
  7. if ($sth->execute() === false) {
  8. echo "error on execute()\n";
  9. print_r($sth->errorInfo());
  10. }

输出

  1. error on execute()
  2. Array
  3. (
  4. [0] => 42000
  5. [1] => 1064
  6. [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
  7. )

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

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

输出

  1. error on prepare()
  2. Array
  3. (
  4. [0] => 42000
  5. [1] => 1064
  6. [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
  7. )
  8. 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相关文章