Search code examples
phpmysqlwhile-loopinfinite-loop

php+mysqli while(false !== ($data = $mysqli_res->fetch_assoc)) creates infinite loop


I wrote an overview for new comments in an admin panel. My code

if($res = $db->query("select * from comments where unlocked=0"));
{
    $o = 0; //abortcondition temp
    echo '<div class="newcomments"><a>neuste kommentare: </a><br />';
    //here is the infinite loop
    while(false !== ($data = $res->fetch_assoc()) && ++$o < 10)
    {
        if($articles = $db->query("select title from coreless_articles where ID=".$data['article']))
        {
            if(false !== ($article = $articles->fetch_assoc()))
            {
                echo 
                '<div id="comment'.$data['ID'].'">'.$data['from'].' in'.
                ' <a href="article/'.($article['uri']).'#comments">'.$article['title'].'</a>'.
                ' <a href="javascript:;">anzeigen</a>'.
                ' <a href="javascript:;">freischalten</a>'.
                ' <a href="javascript:;">l&ouml;schen</a>'.
                ' <div class="preview" >'.$data['text'].'</div>'.
                '</div>';
            }
        }
    }
}

creates an infinite loop, if I don't have the $o abort condition. But I want to show all new comments, not just ++$o < n. I use mysqli to access the database.

any ideas?


Solution

  • mysqli_result::fetch_assoc returns NULL when it's empty, not FALSE. http://www.php.net/manual/en/mysqli-result.fetch-assoc.php

    Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

    Just change your test to NULL !== (etc).

    (This is pretty confusing because the equivalent function mysql_fetch_assoc() does return FALSE.)