当没有找到记录并且失败时,PHP PDO fetch 返回 FALSE
PDO 方法 fetch() 在没有找到记录时返回值 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?
感谢您的宝贵时间.
P.S.:当没有找到记录时,我希望收到一个空数组作为结果,而当出现问题时收到值 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:
- 模拟 PDO 获取失败情况
总之,正如@pucky124 已经说过的,区分很容易实现:
In conclusion, as @pucky124 already said, the differentiation is easy so achieve:
PDOStatement::fetch
如果没有找到记录,则返回FALSE
.PDOStatement::fetch
失败时抛出异常.
PDOStatement::fetch
returnsFALSE
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 中处理错误的一种非常有效的方法.现在您知道了,如果 fetch 返回一个值,则不会发生错误,因此如果它为 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.
相关文章