'Check for PDO Results, If None Display Message, If Yes then Loop Through
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?
Solution 1:[1]
You need not fetch()
but fetchAll()
.
Solution 2:[2]
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.
Solution 3:[3]
Instead of fetch()
, use fetchAll()
.
fetchAll
— Returns an array containing all of the result set rows
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Your Common Sense |
Solution 2 | |
Solution 3 | Devang Rathod |