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
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;
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.