Search code examples
phpmysqlfetchgroup-concatcategorization

Fetch all data from a table grouping by two columns - mysql, php


I am trying to fetch every details I have on my table but group them by two different column names one after other and fetch the same from php

example:

   id   name    url     category    subcategory
/*------------------------------------------------------/*
    1   google  g.gl    partner     associative
    2   fb      f.b     sponsor     main
    3   yahoo   y.ho    partner     color
    4   stack   st.ck   sponsor     main
    5   mys     l.my    sponsor     sub
    6   bang    b.lo    sponsor     parent
    7   xyz     x.yz    partner     color

what I finally want

       id   name    url     category    subcategory
    /*------------------------------------------------------/*
        1   google  g.gl    partner     associative
        3   yahoo   y.ho    partner     color
        7   xyz     x.yz    partner     color
        2   fb      f.b     sponsor     main
        4   stack   st.ck   sponsor     main
        6   bang    b.lo    sponsor     parent
        5   mys     l.my    sponsor     sub

firstly category is grouped and ordered by id, and subcategory is then grouped and ordered by subcategory in ascending order.

also, how could i fetch the same using php

my try:

mysql:

SELECT category, GROUP_CONCAT(subcategory) , GROUP_CONCAT(name) , GROUP_CONCAT(url) 
FROM list
GROUP BY category

PHP:

1. mysql_fetch_array to fetch everything..
2. explode subcategory and every other concated values and then echo them

Solution

  • you can also try this Code:

    <?php 
    $db_resource    = mysqli_connect('Host Name', 'username', 'password');
    $dbconn         = mysqli_select_db('Data base Name', $db_resource);
    $query = 'SELECT * FROM list order by category , subcategory';
    $result = mysqli_query($query);
    while($row = mysqli_fetch_array($result))
    {
        print_r($row);
    
    }
    ?>