dhimo Posted November 16, 2006 Share Posted November 16, 2006 Hello everyone. Anyone have any idea on how to list all the records from this mysql table.As you can see it has main categories and subcategories, wich are identified by parent id and how deep they go.I am using php mysql.So how can i list them where each child is listed under parent id. like a tree menu rightAny ideas anyone? Thanks in advancetbl categories---------------------------------------------------------------------| id | cat_name | parent_id | depth |---------------------------------------------------------------------| 1 | Mobiles | 0 | 0 |---------------------------------------------------------------------| 2 | Computers | 0 | 0 |---------------------------------------------------------------------| 3 | Nokia | 1 | 1 |---------------------------------------------------------------------| 4 | Motorola | 1 | 1 |-----------------------------------------------------------------------| 5 | N70 | 3 | 2 |----------------------------------------------------------------------| 6 | KRZR | 4 | 2 |----------------------------------------------------------------------| 7 | Acer | 2 | 1 |------------------------------------------------------------------------| 8 | IBM | 2 | 1 |------------------------------------------------------------------------| 9 | TravelMate | 7 | 2 |-----------------------------------------------------------------------| 10 | ThinkPad | 8 | 2 |------------------------------------------------------------------------ Link to comment Share on other sites More sharing options...
justsomeguy Posted November 17, 2006 Share Posted November 17, 2006 You will want to use a recursive function to display everything. A recursive function is a function that calls itself. The function will be set to display all of the categories for a certain parent, and for each one it finds it will call itself and display all of the children for that category. It will be something like this: function show_categories($parent = 0, $depth = 0){ $retval = ""; $indentval = " "; $result = mysql_query("SELECT * FROM categories WHERE parent_id={$parent}"); while ($row = mysql_fetch_assoc($result)) { for ($i = 0; $i < $depth; $i++) $retval .= $indentval; $retval .= $row['cat_name']; $retval .= show_categories($row['id'], $depth + 1); } return $retval;} That should give you a good start, you can add links or a table layout or little folder icons or a different way to indent or whatever else you want. I didn't use the depth field in the database btw, the function keeps track of depth on its own. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now