PHP, MySQL – Recursive function to get category for N-Level in tree format

PHP, MySQL – Recursive function to get category for N-Level in tree format
- Create table tbl_categories with catid, catname and catpid (default zero)
This is tested function. Contact me if any problem

  1. NLevelDropdown('category', ", ", ", 0, 0);
  2.  
  3. function nLevel_dropdown($name, $sel_value, $extra=", $choose_one=", $parent_id=0, $level=0){
  4. $level++;
  5. $sql = "select catid, catname from tbl_categories where catpid = '$parent_id'";
  6. $result = mysql_query($sql);
  7. if(mysql_num_rows($result)>0){
  8. if($level==1){
  9. $str_drop .= '{put select tag}'; //<select name="'.$name.'" id="'.$name.'" '.$extra.'>
  10. if($choose_one != "){
  11. $str_drop .= '<option value="">'.$choose_one.'</option>';
  12. }
  13. }
  14. while($line = mysql_fetch_array($result)){
  15. $str_drop .= '<option value="'.$line[0].'" ';
  16. if($sel_value == $line[0]){
  17. $str_drop .= 'selected';
  18. }
  19. $str_drop .= '>';
  20. for($i=1;$i<$level;$i++){
  21. if($i==$level){
  22. $str_drop .= "  »";
  23. }else{
  24. $str_drop .= "»";
  25. }
  26. }
  27. $str_drop .= $line[1].'</option>';
  28. $str_drop .= NLevelDropdown($name, $sel_value, $extra, $choose_one=", $line[0], $level);
  29. }
  30. $str_drop .= $level==1?'</select>':";
  31. }
  32. return $str_drop;
  33. }

2 thoughts on “PHP, MySQL – Recursive function to get category for N-Level in tree format

  1. Pingback: My Homepage

Leave a Reply

Your email address will not be published. Required fields are marked *


three × 7 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>