Best Practices with DB Query Return Types

A

Anonymous

Guest
I am delighted to see PHP's support for strict return type declarations.
However, I keep wrestling with what is the 'best' approach for handling DB queries that should return, say, an array but may return 'false' if the entry is not found.
It would be nice if declaring the return type as nullable (e.g. fcn(): ?array) would work, but it doesn't -- false is not null.

One approach is to use a ternary operation on the query result; e.g.
Code:
return $result ?: null;
An alternate method is to use a try/catch block on the calling function and catching the TypeError when the return is not the correct type.
Of course, there may be better methods, and I would appreciate any suggestions.
Thanks, Bob
 
I think that what you may be looking for is count, assuming you are using PDO (considered best practice) something like this:
Code:
$results = $db->prepare($sql);
$results->execute($parameters);
$count = $results->rowCount();
if ($count === 0){
  return NULL; # or whatever you want
}
return $results->fetchAll(); # returns array
 
Back
Top