0

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
}   

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

@prosportal we've all been there. Sometimes you just need that second pair of eyes to look at the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.