while($ stmt-> fetch())不获取所有数据

时间:2012-01-17 05:03:53

标签: php fetch

我找不到我的功能没有获得所有结果的原因。当我进入页面查看评论时,我只看到最不满意的评论。如果我删除该评论,则会显示下一条最新评论。我确信这件事很简单,我没有注意到。

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;
}

4 个答案:

答案 0 :(得分:4)

我已经弄清楚了。我正在打开一个绑定语句,然后在ViewComment()函数中打开另一个绑定语句以从其他表中获取更多信息。修复方法是将bindResults存储到一个数组中,该数组将由while填充,然后关闭该bind语句。然后在for循环中循环遍历while的结果,该循环调用ViewComment(),其中pramitors是来自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;
} 

答案 1 :(得分:0)

fetch()将只获取一条记录,以获取所有记录使用fetchAll(),更改代码

while($stmt->fetchAll())

答案 2 :(得分:0)

请改变 array_push($ commentArray,$ thisComment); 到

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

答案 3 :(得分:0)

我认为您应该使用以下

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

而不是

$stmt->bind_param('i', $inPostID);
相关问题