1

Because I have so many categories, I created a single "categories" database table :

"id_category , parent_id , category_name , category_tag"

example :

  ----------------------------------------------------------
  | id_category | parent_id | category_name | category_tag |
  ----------------------------------------------------------
  | 1           | 0         | Cars          | cars         |
  | 2           | 1         | Parts         | parts        |
  | 3           | 2         | Accesories    | accesories   |
  ----------------------------------------------------------

the tree :

  Cars
     |_Parts
           |_Accesories

My problem occurs when I want to delete all records in the tree. How do I delete all records in the tree branch from above example.

Is that possible in mySQL with PHP?

4 Answers 4

2

Look up InnodB, that is type of database engine your site is probably using MyISAM at the moment, also look up Cascade Deletes.

InnobDb lets you assign relationships between indicies in your table, you can then assign an action as to what happens when a row is deleted or updated.

You want to set the ON DELETE action to CASCADE, this will cascade the delete operation to child rows and their child rows. So deleting a parent will automatically delete all children, grand children, etc.

Sign up to request clarification or add additional context in comments.

1 Comment

I just read mysql doc...Seems is working.Thank you very much for indications.
1

http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

What you're looking for is a foreign key on parent_id that references id_category with constraint ON DELETE CASCADE. Then you can just delete the root element (category_id 0) and you should end up with an empty table.

Comments

0

A database table is not essentially a tree what you would normally do is

DELETE FROM categories WHERE id_category=3

or

DELETE FROM categories WHERE id_category=3 AND parent_id=2

1 Comment

This isn't scalable at all. Avoid.
0

If you don't have key with constraint, you can delete everything just by a TRUNCATE command on the table.

If you do have a key configured for cascade deletion, deleting the top item (parent_id=0) will delete all the depending and subdepending rows. In this case, deleting the first row would empty the table.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.