-3

Here is the structure of my MySQL table.

enter image description here

I have many results. Many of them have same Brand for example many of them have Brand - Orrange, many of them have Brand - Oddiboss and Brand - Guma.

So my question is how can i display them like this:

enter image description here

I think i have to use while loop.

$r = mysql_query("SELECT * FROM `products`");

while($rowi = mysql_fetch_array($r))
        {

        $id = $rowi['id'];
        $Title = $rowi['Title'];
        $Brand = $rowi['Brand'];
        }

So with this MySQL quesry i can fetch all the results but i can not group them into 3 results displaying how many occurencies everyone have.

I hope you understand what i need.

Venelin
  • 2,905
  • 7
  • 53
  • 117

3 Answers3

2

This query should do it:

SELECT Brand, COUNT(*) AS count 
FROM products 
GROUP BY Brand

It should produce these results:

+----------+-------+
| Brand    | count |
+----------+-------+
| Orange   | 23    |
| Oddiboss | 342   |
| Guma     | 2     |
+----------+-------+

While you really shouldn't be using the MySQL extension for accessing the database, here is how you would fetch these results:

$r = mysql_query("SELECT Brand, COUNT(*) AS count FROM `products` GROUP BY Brand");   
while($row = mysql_fetch_array($r))
{
    echo $row['Brand'] . ' ' . $row['count'] . "<br />\n";
}
Community
  • 1
  • 1
nickb
  • 59,313
  • 13
  • 108
  • 143
0

You should group by brand column as below :

Select Brand, COUNT(*) AS count FROM products group by Brand
AnkiiG
  • 3,468
  • 1
  • 17
  • 28
-1
$sql = SELECT Brand, COUNT(*) AS count FROM products GROUP BY Brand
[...]
echo $row['COUNT(*)'];
Mo Mononoke
  • 175
  • 1
  • 11