while ($ stmt-> fetch ()) Не получает все данные - PullRequest
0 голосов
/ 17 января 2012

Я не могу найти причину, по которой моя функция не дает всех результатов. Когда я захожу на страницу, чтобы посмотреть комментарий, я вижу только самый последний. Если я затем удалю этот комментарий, появится следующий новый комментарий. Я уверен, что это нечто простое, чего я не заметил.

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 ]

4 голосов
/ 17 января 2012

Я понял это.Я открывал оператор связывания, а затем в функции ViewComment () открывал другой оператор связывания, чтобы получить дополнительную информацию из других таблиц.Исправление состояло в том, чтобы сохранить bindResults в массиве, который будет заполнен оператором while, а затем закрыть этот оператор связывания.Затем переберите количество результатов, которые выдает while, в цикле for, который вызывает ViewComment () с прамиторами, являющимися массивом из массива 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;
} 
0 голосов
/ 17 января 2012

Пожалуйста, измените array_push ($ commentArray, $ thisComment); до

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

0 голосов
/ 17 января 2012

Я думаю, вам следует использовать следующее

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

вместо

$stmt->bind_param('i', $inPostID);
0 голосов
/ 17 января 2012

fetch () выберет только одну запись, чтобы извлечь все записи. Используйте fetchAll (), измените ваш код как

while($stmt->fetchAll())
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...