سؤال

I'm a mySQL newbie - usually never use more than INSERT, SELECT statements...

After looking at some SO posts like this question or this one. I'm not sure I get it.

My (simplified) scenario:

I have two tables.

Table1 is named "titles" and has 3 columns: id, pagetitle, pages_id
Table2 is named "pages" and has 2 columns: id, content

In a form I am submitting 2 form fields: title, content

Now, I want to insert each value in each table, but of course I want to make sure that titles.pages_id is the same value as pages.id. Both titles.id and pages.id are auto-increment.

This is not a PHP question

I know how to do this using PHP by making two separate sql statements and using mysqli_insert_id() from the first query in the second one.

But I think there is a SQL-only way of doing a multi-insert query... or is there?

Thanks.

هل كانت مفيدة؟

المحلول

The auto increment won't stop you from inserting a specific id. just insert into one table first and use that id when inserting into the 2nd table.

نصائح أخرى

After some more experimenting I came up with this statement

INSERT INTO pages (`content`) VALUES('hello world'); 
INSERT INTO titles (`pagetitle`, `pages_id`) VALUES ('hw page', LAST_INSERT_ID());

Looks like there is no problem doing things this way. it seems to work fine.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top