atholon Posted May 23, 2008 Share Posted May 23, 2008 Hi there, So I made this table called categories for my site: categoryid int(11) title varchar(255) description varchar(255) parentid int(11) I want to loop through the categories and display a list of everything...in a hierarchy like this: MainCategory - SubCat ---SubCatOfSubCat -----SubCatofSubCat AnotherMainCat - SubCat ----SubCatofSubcat etc... The goal is to to have limitless categories for the website. How should I go about doing this? My friend told me to use a class but I am not sure how to go about it. Could someone help? Link to comment https://forums.phpfreaks.com/topic/107014-categories-mysql/ Share on other sites More sharing options...
Barand Posted May 23, 2008 Share Posted May 23, 2008 You need a recursive function <?php function listSubcats ($parent, $level=0) { $sql = "SELECT categoryid, title FROM categories WHERE parentid = $parent"; $res = mysql_query($sql); while (list($id, $title) = mysql_fetch_row($res)) { $indent = str_repeat('---', $level); echo "$indent $title<br/>"; listSubcats ($id, $level+1); // list its subcats } } listSubcats (0) ; // call for top level ?> Link to comment https://forums.phpfreaks.com/topic/107014-categories-mysql/#findComment-548611 Share on other sites More sharing options...
atholon Posted May 24, 2008 Author Share Posted May 24, 2008 Ok I will try that, thanks! Link to comment https://forums.phpfreaks.com/topic/107014-categories-mysql/#findComment-548624 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.