Paul Paul - 1 month ago 4
MySQL Question

SELECT query only outputting one result

I am running into an issue with a

SELECT
query. The query is only outputting one result, instead of all of the rows in this database.

Does anyone see why?

$select_comments_sql = "
SELECT *
FROM home_comments
ORDER BY id DESC
";
if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
//$select_comments_stmt->bind_param("s", $user_id);
$select_comments_stmt->execute();
if (!$select_comments_stmt->errno) {
//echo "error";
}
$select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date);

$comment_array = array();
while ($select_comments_stmt->fetch()) {
$comment_array[] = $comment_user_id;
$comment_array[] = $comment_username;
$comment_array[] = $home_comments;
$comment_array[] = $comment_date;
}
if ($home_comments === NULL) {
echo 'No comments found.';
} else {
echo $comment_username. "<br>";
echo $home_comments. "<br><br><br>";
}
}

Answer

You are outputting the results outside of the while loop. Since you're storing the entire result set into the $comment_array[], you could dump this as well, to get all the comments fetched from DB or, alternatively, output them inside the loop.

if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
    //$select_comments_stmt->bind_param("s", $user_id);
    $select_comments_stmt->execute();
    if (!$select_comments_stmt->errno) {
        //echo "error";
    }
    $select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date);

    $comment_array = array();
    while ($select_comments_stmt->fetch()) {
        $comment_array[] = $comment_user_id;
        $comment_array[] = $comment_username;
        $comment_array[] = $home_comments;
        $comment_array[] = $comment_date;
        if ($home_comments === NULL) {
            echo 'No comments found.';
        } else {
            echo $comment_username. "<br>";
            echo $home_comments. "<br><br><br>";
        }
    }
    // Alternatively: print_r($comment_array);
}