确保PDO获取方法的结果为“假".是错误或空结果 [英] ensure that PDO fetch method result "false" is a error or empty result

查看:58
本文介绍了确保PDO获取方法的结果为“假".是错误或空结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何识别php PDO mysql驱动程序的执行错误导致的读取错误或空结果?

How can I recognize a fetch error or empty result from a execute error with php PDO mysql driver?

  $sql = ' SELECT * ';
  $sql .= ' FROM test ';
  $sql .= ' WHERE id = 432 ';

  $statement = $this->_db->prepare($sql);
  $status = $statement->execute();

  var_dump($status);

  $result = $statement->fetch(\PDO::FETCH_ASSOC);

  var_dump($result);

  output:
  bool(true)
  bool(false)

因此,我准备了pdo语句,然后执行sql,并且由于没有错误,所以状态为true.然后,我获取结果,在这种特定情况下,id = 432的行不存在.因此fetch方法返回false.我的问题是,当发生错误时,fetch方法也会返回false!

So, I prepare statement with pdo, then execute sql, and status is true because there aren't error. Then I fetch result, and in this specific case a row with id = 432 isn't exist. So fetch method return false. My problem is that fetch method return false also when there is a error!.

如何确定获取假"结果是错误还是空结果?

How can I sure that fetch "false" result is a error or empty result?

推荐答案

如果出现错误,则PDO会引发一个异常,您可以捕获该异常.用try catch包装您的代码,并且应该捕获所有异常.

If there's an error then PDO will throw an exception which you can catch. Wrap your code with a try catch and that should catch any exceptions.

try {
    $rs = $db->prepare('SELECT * FROM foo');
    $rs->execute();
    $foo = $rs->fetchAll();
} catch (Exception $e) {
    echo 'Error: '.$e->getMessage();
}

这篇关于确保PDO获取方法的结果为“假".是错误或空结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆