PHP & MySQL How to display categories any sub categoires from database -


i wondering how display hierarchical data create categories , endless sub categories using php & mysql?

a quick example of how php & mysql code should out lot.

mysql table categories structure

id  parent_id   category 1   0           & w 2   0           b & f 3   1           c & y 4   1           d 

of course it's possible. code render <ul> <li> hierarchical tree, regardless of number of levels

<?php   //connect mysql server   $cn = mysql_pconnect("server", "username", "password");   mysql_select_db("database_name");   $rs = mysql_query("select id, parent_id, category categories", $cn);   $childrentree = array(); //will store array of children each parent   $categorynames = array(); //will store category name each id   //we fill $childrentree ,  $categorynames database   while($row = mysql_fetch_array($rs)){      list($id, $parent_id, $category) = $row;           $categorynames[(string)$id] = $category;      $parent_id = (string)$parent_id;      if(!array_key_exists($parent_id, $childrentree))           $childrentree[$parent_id] = array();      $childrentree[$parent_id][] = (string)$id;   }   //main recursive function. i'll asume '0' id root node  function rendertree($parent = "0"){     global $categorynames;     global $childrentree;     if($parent != "0") echo "<li> ", $categorynames[$parent], "\n";     $children = $childrentree[$parent];     if(count($children) > 0){ //if node has children        echo "<ul>\n";        foreach($children $child)           rendertree($child);        echo "</ul>\n";     }     if($parent != "0") echo "</li>\n";  }  rendertree();  //this renders hierarchical tree ?> 

the resulting html example be:

<ul>     <li> & w     <ul>         <li> c & y </li>         <li> d </li>     </ul>   </li>   <li> b & f </li> </ul> 

that render in browser this:

  • & w
    • c & y
    • d
  • b & f

i repeat, works level of nesting. hope helps.


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -