PDOStatement::fetch occasionally returns false, bu

2019-08-26 08:57发布

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()

标签: php mysql pdo
1条回答
该账号已被封号
2楼-- · 2019-08-26 09:35

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.

查看更多
登录 后发表回答