So I am trying to delete from multiple tables (in this scenario 6). I tried using INNER JOINS to delete rows from them all in one query, but couldn’t get it to work.
Here is my obnoxious work around:
// Delete course and everything linked to it (topics, badges, dotpoints, questions & answers)
$topic = $this->db->query("SELECT * FROM course_topics WHERE course_id = ".$row_id);
foreach ($topic->result() as $t)
{
$badge = $this->db->query("SELECT * FROM course_topic_badges WHERE topic_id = ".$t->id);
foreach ($badge->result() as $b)
{
$dotpoint = $this->db->query("SELECT * FROM course_topic_dotpoints WHERE badge_id = ".$row_id);
foreach ($dotpoint->result() as $d)
{
$question = $this->db->query("SELECT * FROM quiz_questions WHERE dotpoint_id = ".$d->id);
foreach ($question->result() as $q)
{
$answer = $this->db->query("SELECT * FROM quiz_answers WHERE question_id = ".$q->id);
foreach ($answer as $a)
{
$this->db->query("DELETE FROM quiz_answers WHERE question_id = ".$q->id);
}
$this->db->query("DELETE FROM quiz_questions WHERE dotpoint_id = ".$d->id);
}
$this->db->query("DELETE FROM course_topic_dotpoints WHERE badge_id = ".$b->id);
}
$query = $this->db->query("DELETE FROM course_topic_badges WHERE topic_id = ".$t->id);
}
$query = $this->db->query("DELETE FROM course_topics WHERE course_id = ".$row_id);
}
$query = $this->db->query("DELETE FROM courses WHERE id = ".$row_id);
How can I simplify this?
You can simplify this bit:
to simply
$this->db->query(“DELETE FROM quiz_answers WHERE question_id = “.$q->id);
The other option (if you have permission) is to set up foreign keys and “ON DELETE CASCADE”. http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
Otherwise, without knowing the database structure it’s going to be difficult to receommend much more. You could use sub-selects but you’d still need some cascading.
Another option would be to change the DB structure to include primary keys based off more than one field (e.g course_topic_dotpoints would be “topic_id, badge_id, dotpoint_id”) then you can delete more in one go – but this probably requires a fair bit of changing.