【问题标题】:PHP - Infinite while loop from classPHP - 类中的无限循环
【发布时间】:2020-05-06 00:49:30
【问题描述】:

我正在尝试从类调用 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
}   

【问题讨论】:

    标签: php function loops class


    【解决方案1】:

    您的问题是,每次您调用 $post->getRecent() 时,它都会再次执行您的查询,因此 $post->getRecent()->fetch() 然后一遍又一遍地返回结果集的第一行。只需拨打一次$post->getRecent() 并使用该值代替其他电话:

    $post = NEW Posts($db);
    $result = $post->getRecent();
    echo $result->rowCount();
    while ($row = $result->fetch()) {
        // process rows
    }
    

    【讨论】:

    • @prosportal 我们都去过那里。有时您只需要第二双眼睛来查看代码。
    猜你喜欢
    • 2011-11-19
    • 2013-06-02
    • 1970-01-01
    • 2017-10-08
    • 2014-05-30
    • 1970-01-01
    • 2017-06-20
    • 2021-10-23
    • 1970-01-01
    相关资源
    最近更新 更多