I’m making an application that is similar to stackoverflow in that it has ratings for questions and answers and I also have tabs that show comments by oldest, newest and votes. I’m having trouble sorting by votes.
Here is my function:
/**
*
* @param int $threadid
* @param string $tab
* @param object $voting referencing Voting.class.php (may not be needed)
* @return database query/array
*/
public function getComments($threadid, $tab = 'oldest', $voting = null) {
if ($tab == 'oldest') {
$sql = "SELECT * FROM comments WHERE threadid = :threadid ORDER BY date ASC";
} else if ($tab == 'newest') {
$sql = "SELECT * FROM comments WHERE threadid = :threadid ORDER BY date DESC";
} else if ($tab == 'votes') {
//i dont know what to do here? read below for more explanation
} else {
$sql = "SELECT * FROM comments WHERE threadid = :threadid ORDER BY date ASC";
}
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':threadid', $threadid);
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $row;
}
Here is my database design:
**comments:** | id | userid | threadid | message | date |
**commentsrating:** | userid | commentid | voteup | votedown |
If ratings are in a separate table from comments is it possible to make a query for $tab == 'votes' that will conform with the rest of the code?
and finally HTML:
<?php //Get comments
if (isset($_GET['tab'])) {
$getComments = $thread->getComments($threadid, $_GET['tab'], $voting);
} else {
$getComments = $thread->getComments($threadid);
} ?>
<?php for ($i = 0; $i < count($getComments); $i++) { ?>
<p>
<?php echo $getComments[$i]['message']; ?>
</p>
<p>
<span class="bid_votes_count" id="bid_votes_count<?php echo $getComments[$i]['id'] ?>">
<?php echo $voting->getEffectiveCommentVotes($getComments[$i]['id']) . " votes"; ?>
</span>
<span class="bid_vote_buttons" id="bid_vote_buttons<?php echo $getComments[$i]['id'] ?>">
<a href="javascript:;" class="bid_vote_up" id="<?php echo $getComments[$i]['id'] ?>"></a>
<a href="javascript:;" class="bid_vote_down" id="<?php echo $getComments[$i]['id'] ?>"></a>
</span>
</p>
<?php } ?>
Thanks in advance!
Add
ratingfield to thecommentstable and maintain it manually or with trigger oncommentsratingtable.Obviously, put there pre-calculated value of the rating and now you are able to have a simple and terrible fast question to perform.