簡體   English   中英

while($ stmt-> fetch())不獲取所有數據

[英]while($stmt->fetch()) Not fetching all data

我找不到我的函數無法獲得所有結果的原因。 當我轉到該頁面查看評論時,我只會看到最討厭的評論。 如果我隨后刪除該評論,則會顯示下一個最新評論。 我確信這是我沒有注意到的簡單事情。

function getComments($inPostID=null)
{
    $commentArray = array();

    if (!empty($inPostID))
    {
        //echo " Get comments for the post with the postID of ". $inPostID;
        $stmt = db::connect()->prepare("SELECT * FROM Comments WHERE postID = ? ORDER BY commentDate DESC");
        $stmt->bind_param('i', $inPostID);
        $stmt->execute(); 
        $stmt->bind_result($commentID, $postID, $userID, $commentDate, $commentContent);
        while($stmt->fetch())
        {
            echo"HI ";
            $thisComment = new ViewComment($commentID, $postID, $userID, $commentDate, $commentContent);
            array_push($commentArray, $thisComment);
        }
        $stmt->close();
    }

    return $commentArray;
}

我已經知道了。 我正在打開一個綁定語句,然后在ViewComment()函數中打開另一個綁定語句以從其他表中獲取更多信息。 解決方法是將bindResults存儲到一個由while填充的數組中,然后關閉該bind語句。 然后循環遍歷結果的數量,而while則提供了一個for循環,該循環調用ViewComment(),而pramitor是bindResults數組中的數組。

代碼如下。

function getComments($inPostID=null)
{
    $commentArray = array();
    $tempArray = array();

    if (!empty($inPostID))
    {
        //echo " Get comments for the post with the postID of ". $inPostID;
        $stmt = db::connect()->prepare("SELECT * FROM Comments WHERE postID = ? ORDER BY commentDate DESC");
        $stmt->bind_param('i', $inPostID);
        $stmt->execute();
        $stmt->bind_result($commentID, $postID, $userID, $commentDate, $commentContent);
        while($stmt->fetch())
        {
            $bindResults = array($commentID, $postID, $userID, $commentDate, $commentContent);
            array_push($tempArray, $bindResults);
        }
        $stmt->close();
        $total = count($tempArray);
        for($i = 0; $i < $total; $i++)
        {
            $thisComment = new ViewComment($tempArray[$i][0], $tempArray[$i][1], $tempArray[$i][2], $tempArray[$i][3], $tempArray[$i][4]);
            array_push($commentArray, $thisComment);
        }
    }
    return $commentArray;
} 

fetch()將僅獲取一條記錄,以獲取所有記錄。使用fetchAll(),將代碼更改為

while($stmt->fetchAll())

請更改array_push($ commentArray,$ thisComment);

foreach($ thisComment as $ k => $ v)array_push($ commentArray,$ v);

我認為您應該使用以下內容

$stmt->bind_param(1, $inPostID);

代替

$stmt->bind_param('i', $inPostID);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM