我有一个mySQL数据库表,该表的列对应于已投票的图像。值是001.jpg-013.jpg。我需要弄清楚每个图像被投票了多少次。我尝试了以下代码,并得到002.jpg的计数,但没有其他图像。截至目前,至少有25票。这是我尝试使用的代码:
<?php $db = mysql_connect("xxx", "xxx", "xxx"); mysql_select_db("club",$db); $q = mysql_query("SELECT image FROM january"); $array = mysql_fetch_array($q); $results = array_count_values($array); for each while (list ($key,$val) = each($results)) { echo "$key -> $val <br>"; } ?>
我知道array_count_values()是计算每次投票的次数的方法,但是我能找到的所有示例都没有显示如何将其与mySQL配对。任何帮助,将不胜感激!
您需要GROUP BY和COUNT():
SELECT image, COUNT(*) as votes FROM january GROUP BY image
这将返回两列:1表示图像,1表示该图像的投票数:
image votes 001.jpg 1 002.jpg 32 ...
完整代码:
$db = mysql_connect("xxx", "xxx", "xxx"); mysql_select_db("club",$db); $q = mysql_query("SELECT image, COUNT(*) as votes FROM january GROUP BY image"); $votes = array(); while ($row = mysql_fetch_assoc($q)) { $votes[$row['image']] = $row['votes']; } // $votes is an array of 'image' => 'votes' foreach($votes as $image => $count) { echo "$image: $count<br>"; }