The code below do make a category tree with unlimited depth.
I agree that Javascript is great but there should be an alternative to people who doesn't have Javascript enabled.
The whole thing about using AJAX to re-load part of the page sounds smart but I can predict huge compatibility problems and therefore don't want to do it.
<?php
function maketree($rootcatid,$sql,$maxlevel){
// $sql is the sql statement which fetches the data
// you MUST keep this order:
// 1) the category ID, 2) the parent category ID, 3) the name of the category
$mysqli = mysqli_connect('localhost', 'username', 'password', 'databasename');
$result = mysqli_query($mysqli,$sql);
while(list($catid,$parcat,$name)=$row=mysqli_fetch_array($result)){
$table[$parcat][$catid]=$name;
$partable[$catid][$parcat]=$name;
};
$result=buildparent($rootcatid,$table,$partable)."<br>";
$result.=makebranch($rootcatid,$table,0,$maxlevel);
RETURN $result;
}
// this function builds the branches,
// sorting them in alphabetical order
function makebranch($parcat,$table,$level,$maxlevel){
$list=$table[$parcat];
asort($list); // here we do the sorting
while(list($key,$val)=each($list)){
// do the indent
if ($level=="0"){
$output="<img src=./images/se.gif width=12 height=12><a href=\"productlisting.php?cat_id=$key\" onclick=\"ToggleShow('subcat')\">$val</a><br />\n";
}else{
$width=($level+1)*24;
$output="<div id=\"subcat\" style=\"display:none\"><img src=./images/e.gif width=$width height=12><a href=\"productlisting.php?cat_id=$key\">$val</a> $parcat</div><br />\n";
};
// the resulting HTML - feel free to change it
// $level is optional
$result.= $output;
if ((isset($table[$key])) AND (($maxlevel>$level+1) OR ($maxlevel=="0"))){
$result.= makebranch($key,$table,$level+1,$maxlevel);
};
};
RETURN $result;
}
// this function makes the list of the parent categories
// this function is optional
function buildparent($catid,$table,$partable){
if ($catid!=0){
$list=$partable[$catid];
$result=each($list);
$output="<a href=productlisting.php?cat_id=$result[0]>$result[1]</a> / ";
$output=buildparent($result[0],$table,$partable).$output;
};
RETURN $output;
}
?>