Group mysql results by category and display them into groups under each category

后端 未结 4 801
别跟我提以往
别跟我提以往 2020-12-07 02:27

I am trying to create a simple css menu that gets the data from a mysql table.

My idea is to have menu like this

    Category 1
    - link 1
    - li         


        
4条回答
  •  既然无缘
    2020-12-07 03:08

    SQL GROUP BY statement groups the results so that only one row is returned for each category. This is typically used in conjunction with an aggregate function like count(), to count how many items are in each category. What you need is an either ORDER BY as GhostGambler said, or a separate query for each category as shown bellow. However as you only seem to have 2 categories, this approach seems unnecessarily complicated.

     $q=$db->query("SELECT DISTINCT category FROM content ORDER BY category");
     foreach($q as $cat){
        echo '
  • '; echo ''.$cat['category'].''; echo '
  • '; }

提交回复
热议问题