Question

I have three tables that essentially cascade down, like:

  • topic
  • section (references topic id)
  • subsection (references topic id and section id)

Whats the best method of writing mysql statements to create the initial topic/section/subsection so I can grab the id's (auto_incremented) of the newly created rows and use them to insert them into the second two?

edit I'm using phpbb3, dunno if that makes a huge difference, but I normally use the $db-sql_query() function

Was it helpful?

Solution

From the parent, down the line.
Then you can use either LAST_INSERT_ID(), or INSERT in the SELECT:

INSERT INTO TOPIC
  (topic_id, topic)
VALUES (DEFAULT, $topic);

INSERT INTO SECTION
  (topic_id, section)
SELECT topic_id, $section
  FROM TOPIC
 WHERE topic = $topic

INSERT INTO SUBSECTION
  (section_id, topic_id, subsection)
SELECT section_id, topic_id
  FROM SECTION 
 WHERE section = $section

This example assumes that TOPIC.topic_id, SECTION.section_id, and SUBSECTION are auto_increment, primary key columns.

OTHER TIPS

You can use mysql_insert_id() to get the last insert ID. see reference for more details.

As far as I understand, there's only one way, which is top-down.
To add a subsection to a section, you must have had a section already inserted.
To add a topic to a subsection, make sure you added the subsection first.
On the way, you keep track of the last inserted ID (if you just created it) to give it to the next entity down the line.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top