我有一个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配对。任何帮助将不胜感激!
答案 0 :(得分:3)
您需要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>";
}