Code for displaying categories and subcategories using PHP

Discussion in 'PHP' started by dsingh, Mar 28, 2007.

  1. #1
    Hi All
    Can anybody share code for displaying categories and subcategories with me

    Example Main Category->Subcategory->Child category->Child Subcategory-> upto any level
    Thanks
     
    dsingh, Mar 28, 2007 IP
  2. linkstraffic

    linkstraffic Well-Known Member

    Messages:
    388
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    133
    #2
    
    while(loop into Main categ)
    {
    
        while(loop into subcateg)
        {
            while(loop into subofsubcateg)
            {
            ..... up to any level
             }
    
         }
    }
    
    PHP:
    but you better not go far in depth and you should not get too many categories as well other wise that kind of query will take a long time and consume a lot resources...
    You could also go with recursive queries but Php is not a recursive language!
     
    linkstraffic, Mar 29, 2007 IP
  3. linkstraffic

    linkstraffic Well-Known Member

    Messages:
    388
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    133
    #3
    Also it depends how you organize your data; are you using one table or several tables?
     
    linkstraffic, Mar 29, 2007 IP
  4. dsingh

    dsingh Peon

    Messages:
    7
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Iam using only one table
    i need results as follows
    first there are root categories like

    India
    USA
    Canada

    If i click on india next the result is
    india
    >> New Delhi
    >>Bombay
    >>Madras
    USA
    CANADA

    Next if i click on
    >>New Delhi

    The result is
    India
    >>New Delhi
    >>>>Colony 1
    >>>>Colony 2
    >>Bombay
    >>Madras
    USA
    CANADA

    It works on onclick event
    i have a table called Categories
    CID CNAME PID
    1 INDIA 0
    2 USA 0
    3 CANADA 0
    4 New Delhi 1
    5 Bombay 1

    CID is category ID ,PID is parent ID,Cname is name of Category

    Kindly Reply
     
    dsingh, Mar 29, 2007 IP
  5. linkstraffic

    linkstraffic Well-Known Member

    Messages:
    388
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    133
    #5
    So that should be like this to retrieve all:

    
    $query=mysql_query("SELECT name,id FROM yourtable");
    while($l=mysql_fetch_assoc($query))
    {
      $query1=mysql_query("SELECT name,id FROM yourtable WHERE pid=".$l['id']);
      while($l1=mysql_fetch_assoc($query1))
      {
    ....
      }
    
    
    }
    
    
    PHP:
    Then you orgnize your data with your javascript or do some Ajax to display onclick event.
     
    linkstraffic, Apr 5, 2007 IP
  6. Houdas

    Houdas Well-Known Member

    Messages:
    158
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101