PDOStatement::fetch occasionally returns false, but errorInfo() is empty

两盒软妹~` 提交于 2020-01-16 15:47:08

问题


I am having strange problem with PDO. Code is like this:

$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
  $sth = $dbh->prepare("SELECT ... FROM .... ");
  $sth->execute();
  $result = $sth->fetch(PDO::FETCH_ASSOC);
  if (!$result) {
    print_r($dbh->errorInfo());
    print_r($sth->errorInfo());
  }
} catch(PDOException $e) {
  print_r($e->getMessage());
}

So it's very common use of PDO. And the code works as expected most of the time. But occasionally $result is false. What is strange is that both PDO::errorInfo() and PDOStatement::errorInfo() return empty array like this:

array(3) {
  [0]=> string(5) "00000"
  [1]=> NULL
  [2]=> NULL
}

I suspect there is some problem with MySQL connection, however connection works fine, doesn't throw any exceptions, MySQL server is idle, there is enough connections available. There are no errors in MySQL or PHP log.

So my question is, how to troubleshoot this problem more ? I need to know, why sometimes fetch() fails with false and there is no information about error in errorInfo()


回答1:


OK, I have found out what was causing this strange behaviour. I have 2 very similar databases on this MySQL server. And I use persistent connections with both of them. And somehow (???) PHP's PDO is sometimes created with different database selected.

I would never expect this, because in new PDO(); I have right database I need to use. But for some strange reason connection is made to different database. It has to do something with using persistent connections, because when I disable using persistent connection, everything works fine.

So I am probably going to ask another question - this time - why PDO connects to different database when it's supposed to when using persistence.



来源:https://stackoverflow.com/questions/50422388/pdostatementfetch-occasionally-returns-false-but-errorinfo-is-empty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!