1

I have a mySQL database table with a column that corresponds to an image that has been voted on. The values are 001.jpg - 013.jpg. I need to figure out how many times each image has been voted for. I tried the following code, and got a count for 002.jpg, but none of the other images. There are at least 25 votes as of this moment. Here is the code I tried to use:

<?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>";
         }
?>

I understand that array_count_values() is the way to count the occurrence of each vote, but all the examples I can find don't show how to pair this with mySQL. Any help would be appreciated!

1 Answer 1

3

You need GROUP BY and COUNT():

SELECT image, COUNT(*) as votes FROM january GROUP BY image

This will return two columns: 1 for the image, and 1 for the number of votes for this image:

image     votes
001.jpg   1
002.jpg   32
...

Full code:

$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>";
}
Sign up to request clarification or add additional context in comments.

3 Comments

This is great...thanks! I can't quite figure out an echo statement to get this written to the web page. Can you help with that?
foreach($votes as $image => $count) { echo "$image: $count<br>"; }
Very awesome...thanks! I appreciate everyone who took time to help out with this. I learn something new each time!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.