PHP PDO fetch returns FALSE when no records found AND on failure

后端 未结 1 595
借酒劲吻你
借酒劲吻你 2021-01-19 02:38

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 data

相关标签:
1条回答
  • 2021-01-19 03:16

    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 ]
        );
    

    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.

    0 讨论(0)
提交回复
热议问题