Simulate a PDO fetch failure situation

前端 未结 3 1217
無奈伤痛
無奈伤痛 2021-01-20 05:27

Conform to the php docs, the PDO method fetch() returns the value FALSE both when no records are found AND on failure (e.g. when something goes

3条回答
  •  天命终不由人
    2021-01-20 05:48

    Unless you need the PDOStatement for a loop, you can use fetchAll in a method/function to get the result you are looking for. Just do a fetchAll instead of a fetch, check for false, and return as necessary. In this case, your query should make sure only 1 row is returned.

    Something like this;

    function fetch(\PDOStatement $pdo_stmt)
    {
        // use fetchAll as an empty result set is returned by PDO as false using fetch()
        $result = $pdo_stmt->fetchAll(\PDO::FETCH_ASSOC);
        if ($result !== false) {
            return !empty($result) ? $result[0] : [];
        }
        return false;
    }
    
    function fetchColumn(\PDOStatement $pdo_stmt)
    {
        // this will return false if no rows or not found...
        $result = $pdo_stmt->fetchColumn();
        if (empty($pdo_stmt->errorInfo())) {
            return $result !== false ? $result : null;
        }
        return false;
    }
    

    Note that fetchColumn has a similar issue.

    The above will return;

    • false on query failure
    • an empty array for fetch if no rows found
    • appropriate result set for fetch if found
    • null for fetchColumn if not found
    • column value for fetchColumn if found

    Scanning your code sample, you could implement like so;

    $sql  = 'SELECT * FROM users WHERE name = :name';
    $stmt = $connection->prepare($sql);
    $stmt->bindValue(':name', 'Sarah');
    $executed = $stmt->execute();
    
    if (!$executed) {
        throw new UnexpectedValueException('The prepared statement can not be executed!');
    }
    
    $result_set = fetch($stmt);
    if ($result_set === false) {
        throw new UnexpectedValueException('Fetching data failed!');
    }
    // handle result set
    

    There is more you can do to improve the above, but hopefully you get the idea.

提交回复
热议问题