在jquery upvote插件中计算总投票数

vs3odd8k  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(299)

解决这个问题我真的很困惑。目前我的项目中有一个jqueryupvote插件。因此,每次单击upvote,它都会将db中的值保存为true,每次收回投票,它都会将数据库中的值保存为false,并将另一列中的值保存为0。我所要做的就是像堆栈溢出一样计算总投票数。即使是现在,我也对如何解决这个问题感到困惑。最后我用php编写了这段代码,这也让我的整个程序变慢了:

$sample1 = $this->db->prepare("SELECT * from Ratings WHERE TopicID = :current");
$sample1->bindParam(':current', $id);
$sample1->execute();
$RES1 = $sample1->fetchAll(PDO::FETCH_ASSOC); 
$upVote = 0;

foreach ($RES1 as $mk){
     if(($mk['Upvote'] === 'true') && ($mk['Downvote'] ==='false')){
             $upVote++;
                                    }
     else if(( $mk['Upvote'] ==='false') && ($mk['Downvote'] === 'true')){
             $upVote--;
                                }
     else if(($mk['Upvote'] === 'false') && ($mk['Downvote'] === 'false')){
            $upVote--;
                                }
     else if(($mk['Downvote'] === 'false')){
             $upVote++;
                                }
     else if(($mk['Downvote'] === 'true') && ($mk['Upvote'] ==='0') || ($mk['Upvote'] === 'false')){
             $upVote--;
     }

 }

我的表结构:

c3frrgcw

c3frrgcw1#

我认为您应该在数据库端这样做,然后像这样重写您的查询:

SELECT ((SELECT COUNT(*) FROM Ratings WHERE TopicID = :current AND Upvote = true) - (SELECT COUNT(*) FROM Ratings WHERE TopicID = :current AND Downvote = true)) AS total_votes

在php端,只需获取 total_votes :

$sample1 = $this->db->prepare("SELECT ((SELECT COUNT(*) FROM Ratings WHERE TopicID = :current AND Upvote = true) - (SELECT COUNT(*) FROM Ratings WHERE TopicID = :current AND Downvote = true)) AS total_votes");
$sample1->bindParam(':current', $id);
$sample1->execute();
$result = $sample1->fetch(); 
$total_votes = $result->total_votes;

相关问题