Home > front end >  How i can delete id and sub id
How i can delete id and sub id

Time:04-12

I have database like that:

id name_categories id_categories
1 General 0
2 hotnews 1
3 breakingnews 2

Main categories is (General) with id 1 and id_categories =0

Sub catagrois for main (hostnews) id_categories = 1

(breakingnews) is sub main for (hotnews) whith id_categories=2

id linked with id_categories

Whene i want delete general i need delete all id_categories linked with id main and sub main and sub sub main.

How i can do that with PDO PHP;

CodePudding user response:

Correct database design covers this type of tasks automatically:

CREATE TABLE `categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name_categories` varchar(255) NOT NULL,
  `id_categories` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `id_categories` (`id_categories`),
  CONSTRAINT `categories_ibfk_1` FOREIGN KEY (`id_categories`) REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Whenever you delete a row from this table, mysql will also delete all the referencing rows, and rows that reference referencing rows, etc.

You can recursively delete rows with PHP, but this is a bad idea for a number of reasons.

  • Related