PDO prepare silently fails

蹲街弑〆低调 提交于 2019-12-05 05:08:21

My bets are on: $GLOBALS['db'] is not set or not an instance of pdo (anymore?) and therefor a PHP Fatal error: Call to a member function prepare() on a non-object occurs and php bails out.

$sql = 'REPLACE INTO sessions SET id=:id, access=:access, data=:data';
logger('This is the last line in this function that appears in the log.');
if ( !isset($GLOBALS['db']) ) {
  logger('there is no globals[db]');
  return;
}
else if ( !is_object($GLOBALS['db']) ) {
  logger('globals[db] is not an object');
  return;
}
else if ( !($GLOBALS['db'] instanceof PDO) ) {
  logger('globals[db] is not a PDO object');
  return;
}
else {
  logger('globals[db] seems ok');
}

$stmt = $GLOBALS['db']->prepare($sql);
logger('This never gets logged! :(');

Perhaps PDO doesn't recognize the REPLACE INTO syntax. If the underlying DB access library doesn't support prepared statements directly, PDO emulates them, and may not have REPLACE INTO in its list of possible statement types.

Try checking $stmt->errorCode() immediately after the prepare call?

If this is mysql, you could try rewriting the prepared statement as follows:

INSERT INTO sessions (id, access, data)
VALUES(:id, :access, :data)
ON DUPLICATE KEY UDPATE
    access=VALUES(access), data=VALUES(data);

and see if that gets you any farther.

I feel like resource data types can't be accessed via $GLOBALS[]. Something about the way references are handled or something. If you're in the mood to humor my hunch try this for your function declaration:

function _write($id, $data) {
    global $db;
    logger('_WRITE ' . $id . ' ' . $data);
    try {

And instead of this:

$stmt = $GLOBALS['db']->prepare($sql);

try

$stmt = $db->prepare($sql);

You could also try catching plain old Exceptions instead of PDOExceptions; it might be getting caught up on that.

Hope this helps!

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