Recursive Function for Nested Categories

Nested Categories over Drop Down

Nested Categories

Categories and its sub categories are always useful while developing simple to huge applications. Here is a simple php code to create multi-leveled nested categories on select box to those categories.

CREATE TABLE `tb_category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`pid` int(11) NOT NULL,
`name` varchar(255) NOT NULL
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


<?php

/*

Function lists all items in table tb_category

- id

- pid

- name

*/

$HOST="localhost";

$DB="categories";

$USER="root";

$PASS="";

mysql_connect($HOST,$USER,$PASS);

mysql_select_db($DB);

function RecursiveCat($pid)

{

static $level=0;

static $strid="";

static $strname="";

$sql=mysql_query("select * from tb_category where pid = '$pid' order by name ");

while($row=mysql_fetch_assoc($sql))

{

$id=$row['id'];

$level--;

$pad="";

for($p=1;$p<($level*-1);$p++) $pad.="&nbsp;&nbsp;&nbsp;- ";

$strname.='<option value="'.$row['id'].'">'.$pad.$row['name'].'</option>';

$rid=RecursiveCat($id);

$strid[]=$row['id'];

$level++;

}

return $strname;

}

echo '<select name="cat">';

echo RecursiveCat(0);

echo '</select>';

?>