当没有找到记录并且失败时,PHP PDO fetch返回FALSE [英] PHP PDO fetch returns FALSE when no records found AND on failure

查看:288
本文介绍了当没有找到记录并且失败时,PHP PDO fetch返回FALSE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PDO方法 fetch() 在没有发现记录 AND 时返回值 FALSE (例如,当数据库出现问题时访问)。

The PDO method fetch() returns the value FALSE both when no records are found AND on failure (e.g. when something goes wrong regarding the database access).

我需要能够区分两种情况,并以相应的方式处理每一种情况:

I need to be able to differentiate between the two situations and to handle each one in the corresponding manner:


  • 在没有找到记录的情况下向用户显示消息,

  • 在失败时抛出异常。

所以,我的问题是:有没有办法以正确的方式处理结果?

So, my question: is there a way to handle the result in a proper manner?

谢谢对于你的时间。

PS:我没有想到会收到一个空数组,因为没有找到记录,值 FALSE 出现问题时。就像在 fetchAll() 方法。

P.S.: I would have expected to receive an empty array as result, when no records are found, and the value FALSE when something goes wrong. Like in the case of fetchAll() method.

方法 PdoStatement :: fetch 在失败时抛出异常,而不是 FALSE 。在我的答案中证明了这种情况:

The method PdoStatement::fetch throws exceptions on failure, instead of FALSE. Such a case is demonstrated in my answer:

总而言之,正如@ pucky124已经说的那样,差异化很容易实现:

In conclusion, as @pucky124 already said, the differentiation is easy so achieve:


  • PDOStatement :: fetch 返回 FALSE 如果没有找到记录。

  • strong> PDOStatement :: fetch 在失败时抛出异常。

  • PDOStatement::fetch returns FALSE if no records are found.
  • PDOStatement::fetch throws exceptions on failure.

推荐答案

这是什么 PDO :: ATTR_ERRMODE => PDO :: ERRMODE_EXCEPTION 是为。使用它像这样:

This is what PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION is for. Use it like this:

$pdo = new PDO(
            'mysql:host=localhost;port=3306;dbname=mydb;charset=utf8'
            , 'user'
            , 'pass'
            , [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ]
    );

当使用这种方式时,错误实际上被抛出为异常。这意味着如果fetch(或使用此pdo对象的其他方法)发生错误,将抛出异常,并且该方法根本不会实际返回。这是处理PDO中错误的非常有效的方法。现在你知道如果提取返回一个值没有发生错误,因此如果它是false,则查询返回没有记录。

When used this way errors actually get thrown as exceptions. This means that should an error occur with fetch (or other methods using this pdo object) an exception will be thrown and the method won't actually return at all. This is a very effective way of handling errors in PDO. Now you know that if fetch returns a value no errors occured and therefore if it is false then the query returned no records.

这篇关于当没有找到记录并且失败时,PHP PDO fetch返回FALSE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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