1

I have a table in my mysql database that looks like the following:

    id         |   category  |     title   
     1         |     blue    |     title1
     2         |    green    |     title2
     3         |     red     |     title3
     4         |    purple   |     title4
     5         |     red     |     title5
     1         |     blue    |     title1
     2         |    green    |     title2
     3         |     blue    |     title3
     4         |     blue    |     title4
     5         |     red     |     title5

.....

I want to echo the category names on my page and then count how many items there are in each category.

Goal is something like this:

blue(4)
green(2)
red(3)
purple(1)

I have tried echoing the categories but I just receive a long list of duplicates. Can anybody point me in the right direction?

2 Answers 2

3

No need to mess with associative arrays. You can easily do this in SQL using GROUP BY and COUNT. See the MySQL manual for an example.

Sign up to request clarification or add additional context in comments.

1 Comment

MySQL GROUP BY and COUNT is the way to go. See below. Working code: <?php $query = "SELECT category,count(*) AS col_num FROM news GROUP BY category ASC"; $result = mysql_query($query); while($row = mysql_fetch_array($result,MYSQL_ASSOC)) { while(list($key, $value) = each($row)) { if($key!="col_num") $name = $value; else $count[$name]=$value; } } while(list($key, $value) = each($count)) echo "$key ( $value )<br>"; ?>
2

I'm not going to give you code, since you should be trying to write that yourself and since this sounds like homework.

Here's a basic idea of what your PHP script can look like:

  1. Select all rows from your database.
  2. Create an associative array where category name is the key and number of appearances is the value.
  3. Iterate over the table data you got back from your query, and for each category, increment the respective count in your array.

Good luck and feel free to ask another question once you've got some code written.

1 Comment

Thanks for the help. Homework indeed, at least I know where to get started now. Cheers mate.

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.