Reputation: 109
I'm trying to create a while loop from the returned execution of a PDO statement in a class call Posts, but it's creating an infinite while loop even though the number of rows returns correct. This seems simple...Am I writing this wrong?
public function getRecent()
{
$sql = "SELECT * FROM posts ORDER BY createdate DESC LIMIT 5";
$stmt = $this->db->prepare($sql);
$stmt->execute();
return $stmt;
}
$post = NEW Posts($db);
echo $post->getRecent()->rowCount(); //5 results(correct)
while ($row = $post->getRecent()->fetch())
{
//Creates infinite loop
}
Upvotes: 0
Views: 66
Reputation: 147266
Your problem is that every time you call $post->getRecent()
it executes your query again and so $post->getRecent()->fetch()
then returns the first row of the result set over and over again. Just make one call to $post->getRecent()
and use that value in place of the other calls:
$post = NEW Posts($db);
$result = $post->getRecent();
echo $result->rowCount();
while ($row = $result->fetch()) {
// process rows
}
Upvotes: 1