我试图从一个叫做 Posts 的类中的 PDO 语句的返回执行中创建一个 while 循环,但它正在创建一个无限的 while 循环,尽管 行数正确. 这看起来很简单...我是不是写错了?
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
}
你的问题是,每次你调用 $post->getRecent()
它再次执行你的查询,所以 $post->getRecent()->fetch()
然后反复返回结果集的第一行。只需调用一次 $post->getRecent()
并用该值代替其他调用。
$post = NEW Posts($db);
$result = $post->getRecent();
echo $result->rowCount();
while ($row = $result->fetch()) {
// process rows
}