且构网

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

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

更新时间:2023-02-16 18:49:51

这是什么 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.