开发者

php/mysql posting COUNT(*) FROM Poll total yes/no

I'm trying to count the yes and no votes so that I can just post the total yes/no for my website. This is should 开发者_如何学Gobe easy, but I must be missing something somewhere since I don't get a return result. At least no php error. My total vores

$result = mysql_query("SELECT * FROM Poll");

$votes_Poll = mysql_num_rows($result);

$vote_yes = mysql_query("SELECT vote, COUNT(*) FROM Poll GROUP BY yes");
$vote_no = mysql_query("SELECT vote, COUNT(*) FROM Poll GROUP BY no");


// Display the results

echo $votes_Poll;
echo "<br>";
echo $vote_yes;
echo "<br>";
echo $vote_no;

thanks in advance


That's because you're echoing out a query object. Each of your queries should be...

$vote_yes = mysql_query("SELECT COUNT(*) AS total FROM Poll WHERE vote = 'yes' ");
$row = mysql_fetch_object($vote_yes);

echo $row->total; //echoes out the number of yes votes


You are misunderstanding how GROUP BY works. You do not use it to select an answer, it is used to select a field, by which aggregate functions are grouped.

If you use:

SELECT `vote`, COUNT(*) FROM Poll GROUP BY `vote`

Then this will return two results, each with two values, the vote (yes or no) and the count for that vote.

$handle = mysql_query("SELECT `vote`, COUNT(*) AS `count` FROM Poll GROUP BY `vote` ORDER BY `vote` DESC");

if ($handle) {
    $results = mysql_fetch_assoc($handle);
    echo ($results[0]['count'] + $results[1]['count']) . "<br>" . $results[0]['count'] . "<br>" . $results[1]['count'];
}

NB. Using the ORDER BY vote DESC part, that forces the order to yes then no (reverse alphabetical) and then you do not have to check which row is which.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜