When you want to delete a category – it will first delete all the related products with the related groups and attributes. A product have many relationships.
This is how it deal when deleting a category:
if (isset($_POST['catid']) && $_POST['catid'] > 0) {
$category_id = mysql_real_escape_string($_POST['catid']);
$SQL = "SELECT * FROM products WHERE category_id = '$category_id'";
$q_item = mysql_query($SQL);
while ($dItem = mysql_fetch_assoc($q_item)) {
$itemid = $dItem['id'];
$SQL = "SELECT * FROM option_groups WHERE item_id = " . $itemid;
$q = mysql_query($SQL);
while ($option_group = mysql_fetch_assoc($q)) {
$optionGroup = $option_group['id'];
$SQL = "SELECT * FROM options WHERE option_group_id = " . $optionGroup;
$q = mysql_query($SQL);
while ($row = mysql_fetch_assoc($q)) {
$option = $row['id'];
mysql_query("DELETE FROM options WHERE id = " . $option);
mysql_query("DELETE FROM e_groups_options WHERE option_id = " . $option);
}
mysql_query("DELETE FROM option_groups WHERE item_id = " . $itemid);
mysql_query("DELETE FROM products WHERE id = " . $itemid);
}
}
$SQL = "DELETE FROM categories WHERE id = '$category_id'";
mysql_query($SQL);
}
You can see, I have used included many DELETE query and the code look a bit messy, is there alternative way and safer?
Storage Engine is MyISAM and I have over 100,000 rows of data in the tables (fields are indexed).
If these tables were related with a foreign key, you could specify
ON DELETE CASCADEin the foreign key and just delete the Category. You’ll have to switch to InnoDB to be able to apply this. Citing the documentation on foreign keys:Take into account that cascaded actions do not fire triggers.
You can switch your tables to InnoDB with
ALTER TABLE table_name ENGINE = InnoDB.You can add a foreign key with the
ALTER TABLEstatement, for instance:With this foreign key, whenever you issue a
DELETEstatement oncategories, the RDBMS will also delete theproductsreferencing this category.