Reputation: 8509
Trying to find another simple answer but only finding complicated examples.
I'm trying to simply query a table, if there are results to display then loop through them, if there are not then display a message - unfortunately all examples I can find 'fetch' as part of the while loop, not before, so I'm trying to do:
$stm = $PdoObj->prepare("SELECT * FROM NEWS_articles");
$stm ->execute();
$results = $stm ->fetch();
if($results==null){
echo "<p>No dice, try other criteria</p>";
}else{
foreach($results as $row){
echo $row["articleName"];
}
}
The following question is close to what I'm trying to achive but was never answered satisfactorily: Is it possible to check if pdostatement::fetch() has results without iterating through a row?
Upvotes: 1
Views: 1800
Reputation: 10838
As mentioned by Your Common Sense use fetchAll
. If there aren't any results, it will return an empty array:
$results = $stm->fetchAll();
if(empty($results))//or if(!$results) or if(count($results)==0) or if($results == array())
{
echo 'Nothing found';
}
else
{
foreach($results as $result)
{
//do stuff
}
}
The official method for getting how many rows have been returned is rowCount()
:
$stm->execute();
if($stm->rowCount() == 0)
{
echo 'Nothing found';
}
else
{
//do your stuff
}
Though this would not be necessary if you are already calling fetchAll
as this result can be used to determine the size of the result set.
Upvotes: 3
Reputation: 6736
Instead of fetch()
, use fetchAll()
.
fetchAll
— Returns an array containing all of the result set rows
Upvotes: 0