I'm trying to find the number of comments made on each post, and it's working fine when the user is logged out, but if they're logged in it's doing something strange.
If they're logged in I check whether they've upvoted or downvoted something, but I've placed that within an if statement. Maybe it's conflicting?
<?php
if (isset($_SESSION['userid'])){
$stmt = $db->prepare("SELECT pv_type,COUNT(*) FROM post_votes WHERE pv_postid = ? AND pv_userid = ?");
}
$stmt2 = $db->prepare("SELECT COUNT(*) FROM comments WHERE c_postid=?");
foreach($posts as $post):
// [variables set here, removed for this post]
if (isset($_SESSION['userid'])){
$stmt->bind_param("ii",$p_id,$session_id);
$stmt->execute();
$stmt->bind_result($pv_type,$voted);
$stmt->fetch();
}
$stmt2->bind_param("i",$p_id);
$stmt2->execute();
$stmt2->bind_result($numComments);
$stmt2->fetch();
if ($numComments == 1){
$numComments = $numComments . " comment";
} else {
$numComments = $numComments . " comments";
}
?>
** HTML to be rendered **
<div class="comment-info"><?php echo $numComments; ?></div>
<?php
endforeach;
if (isset($_SESSION['userid'])){
$stmt->close();
}
$stmt2->close();
When the user is logged in, it doesn't get the number of comments and on each post it adds another comments, e.g.
post 1 is comments
, post 2 is comments comments
, rather than 1 comment
, 3 comments
, etc.
I must be missing something here