This is my Table:
CREATE TABLE `cats` (
`id` int(9) NOT NULL auto_increment,
`name` varchar(255) default NULL,
`parent` int(9) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=cp1256;
INSERT INTO `cats` VALUES ('1', 'Cat1', '-1');
INSERT INTO `cats` VALUES ('2', 'Cat2', '-1');
INSERT INTO `cats` VALUES ('3', 'Cat3', '-1');
INSERT INTO `cats` VALUES ('4', 'sub1', '1');
INSERT INTO `cats` VALUES ('5', 'sub2', '2');
INSERT INTO `cats` VALUES ('6', 'sub3', '3');
INSERT INTO `cats` VALUES ('7', 'subsub1', '4');
INSERT INTO `cats` VALUES ('8', 'subsubsub1', '7');
<?php
include("inc/config.php");
$DB=new db;
function listSubcats ($parent, $level=0) {
global $DB;
$res = $DB->exe("SELECT id, name FROM cats
WHERE parent = '$parent'
ORDER BY name");
while (list($id, $name) = $DB->fetch_row($res)) {
$indent = str_repeat('>', $level);
echo "<OPTION value='$id'>$indent $name</OPTION>\n";
listSubcats($id, $level+1);
}
}
// End Function tst
echo "<SELECT name='cat'>";
$res=$DB->exe("select * from cats");
while($bb=$DB->fetch_array($res))
{
listSubcats($bb['parent']);
}
echo '</SELECT>';
?>
When i run the code its showen as image below:
Please note that when the parent is -1 its mean that has no parent.
Thanks,