且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当没有找到记录并且失败时,PHP PDO fetch 返回 FALSE

更新时间:2023-02-16 18:45:20

这就是 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.