Reputation: 6663
Assume I have this piece of code:
foreach($creds as $cred){
$prev_fut = $pdo->query("SELECT importo FROM incassi_prev WHERE
data_prev='$data_fut' AND incasso=0 AND
id_cre='{$cred['id_cre']}'")->fetch();
if(count($prev_fut)>0){
//I have found a result
}else{
//I have found nothing
}
}
NOTE: It is an internal query for my application with no data posted by user so I don't worry about SQL injections.
I use to check if count($prev_fut)>0
to see if the query is returning data (if I find any row in the db with these criterias).
My question is:
is this check enough to verify that the query has at least a result? Is it better to perform any other check?
The question is mostly coming from my thoughts about this being in a for loop and is related to the option of emptying/unset the $prev_fut array before starting a new iteration of for loop.
Upvotes: 0
Views: 2918
Reputation: 522024
fetchColumn
returns a single value of the next row in the result set. count
counts the length of an array. Since fetchColumn
can't return an array (for most database implementations), using count
on it is wrong. You want to test whether $prev_fut
is false
or not. false
would indicate that no result could be fetched, while anything else means a result was fetched:
if ($prev_fut !== false) ..
Having said that, you should really use a COUNT()
in the database and check that value:
$result = $pdo->query('SELECT COUNT(*) FROM ...')->fetchColumn();
if ($result > 0) ..
It's much more efficient to have the database count and summarise the result than fetching an entire result set into PHP just for this simple check.
Upvotes: 2