seksislav Posted December 3, 2008 Share Posted December 3, 2008 Hello, I need to make a function that will display all categories and subcategories from a mysql table. In the mysql the table there is something like this: cat_id, cat_root; if cat_root is 0 -> it is a main category. Otherways it means that cat_roots is pointing to the root category. For example: Category 1 ( id 1 | cat_id 0 ) Product 1( id 2 | cat_id 1) SubProcut 1 (id 3 | cat_id 2) Category 2 (id 4 | cat_id 0 ) and so on. I hope you get the picture. I'm looking for a way to call all the categories for a <select>. What I've done so far is something like this: function makeSelectCategories($id = 0 ,$str = '",$spacing=""){ $q = "SELECT * FROM `categories` WHERE `cat_root` = ".$id; $r = mysql_query($q) or die(mysql_error()); if(mysql_num_rows($r) == 0) return false; while($row = mysql_fetch_array($result, MYSQL_ASSOC)){ $str .= "<option>".$spacing.$row['cat_title']."</option>"; $str .= makeSelectCategories($row['cat_id'],$str,$spacing." "); } return $str; } echo "<select>"; echo makeSelectCategories(); echo "</select>"; I hope you get what I mean. Thanks in advance. Link to comment https://forums.phpfreaks.com/topic/135332-recursive-function/ Share on other sites More sharing options...
sasa Posted December 3, 2008 Share Posted December 3, 2008 try function makeSelectCategories($id = 0, $spacing=""){ $q = "SELECT * FROM `categories` WHERE `cat_root` = ".$id; $r = mysql_query($q) or die(mysql_error()); $str = ''; //if(mysql_num_rows($r) == 0) //return false; while($row = mysql_fetch_array($result, MYSQL_ASSOC)){ $str .= "<option>".$spacing.$row['cat_title']."</option>"; $str .= makeSelectCategories($row['cat_id'], $spacing." "); } return $str; } Link to comment https://forums.phpfreaks.com/topic/135332-recursive-function/#findComment-705031 Share on other sites More sharing options...
GingerRobot Posted December 3, 2008 Share Posted December 3, 2008 If you're doing anything with much depth/efficiency is important, the following article would be a good read: http://dev.mysql.com/tech-resources/articles/hierarchical-data.html Link to comment https://forums.phpfreaks.com/topic/135332-recursive-function/#findComment-705110 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.