Best Practices with DB Query Return Types

Codes here !

Moderators: egami, macek, gesf

Post Reply
New php-forum User
New php-forum User
Posts: 1
Joined: Fri Jul 31, 2020 12:33 pm

Fri Jul 31, 2020 1:06 pm

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: Select all

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
User avatar
php-forum GURU
php-forum GURU
Posts: 1222
Joined: Mon Feb 22, 2016 5:52 pm

Fri Jul 31, 2020 1:40 pm

I think that what you may be looking for is count, assuming you are using PDO (considered best practice) something like this:

Code: Select all

$results = $db->prepare($sql);
$count = $results->rowCount();
if ($count === 0){
  return NULL; # or whatever you want
return $results->fetchAll(); # returns array
Post Reply