0
votes

I want to create categories with parent child relation with infinite levels and I have this table categories which has these columns

cat_id               INT             NOTNULL     AUTOINCREAMENT PRIMARY
cat_name             VARCHAR(50)     NOT NULL
parent_id            INT             NULL      
grand_parent_id      INT             NULL

I want to add categories and subcategories with unlimited levels. For example I want to add category Web then I add another category its child 'PHP' then I want to add another category 'Cake' and whose parent is PHP.

So hierarchy should be like this: Web → PHP → Cake where Web is now grandparent, PHP is parent and child of Web, and Cake is child of PHP and grandchild of Web.

My interface is look like this:

  • textfield add category
  • dropdown contains all existing categories which you can select as Parent

If I enter a new category, let us suppose I add Web, its cat_id and cat_name are entered in category table with parent_id and grand_parent_id values of '0'.

Then I insert a new category PHP and select Web as its parent in dropdown; now insertion should be like this: php cat_id and cat_name entries in their columns and in parent_id gets dropdown category value i.e Web and grand_parent_id got value '0'.

Now I insert new category Cake and select PHP as parent in dropdown; now insertion should be like this: cake cat_id and cat_name insert in their columns and in parent_id goes dropdown category id i.e PHP and in grand_parent_id enters values 2 which is Web.

Can you give me any idea how can I do it?

1

1 Answers

1
votes

I think you're over complicating a little. Drop the grand_parent_id as it's a little pointless in these situations. Just record the parent_id then you could use a recursive function to map the categories into an object or array.

Take a look at this article to clarify http://kevin.vanzonneveld.net/techblog/article/convert_anything_to_tree_structures_in_php/

Hope that helps!