我的投票表在数据库中看起来像;

ID      CandidateID
1         205
2         209
3         203
4         205
5         205
6         209


码:

<?php $votes_query=mysql_query("select * from votes where CandidateID='$id'");
$vote_count=mysql_num_rows($votes_query);
echo $vote_count;
?>


上面的代码给出了各个结果,例如CandidateID 205 =3 votesCandidateID 209=2 votes

什么样的代码可以将表中的这些票相加,candidateID 205 + CandidateID 209 = 3+2=5

最佳答案

要按候选人获取所有候选人投票计数:

<?php
  $rs = mysql_query("select CandidateID, count(*) as vote_count from votes group by CandidateID");
  while(mysql_fetch_array($rs)){
    $CandidateID = $rs['CandidateID'];
    $vote_count = $rs['vote_count'];

    echo $CandidateID . " " . $vote_count;
  }

?>


获取所有选定候选人的投票计数

<?php
  $rs=mysql_fetch_array(mysql_query("select count(*) as vote_count from votes where CandidateID in ($id)")); // where look like as $id = "'205','209'";
  $vote_count=$rs['vote_count'];
  echo $vote_count;
?>

关于php - 我想计算特定ID的总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22375578/

10-11 19:23