Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>No, you can't insert into multiple tables in one MySQL command. You can however use transactions.</p> <p>BEGIN INSERT INTO users (username, password) VALUES('test', 'test') INSERT INTO profiles (userid, bio, homepage) VALUES(LAST_INSERT_ID(),'Hello world!', '<a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a>'); COMMIT;</p> <p>Have a look at LAST_INSERT_ID to reuse autoincrement values. Edit: you said "After all this time trying to figure it out, it still doesn't work. Can't I simply put the just generated ID in a $var and put that $var in all the MySQL commands?"</p> <p>Let me elaborate: there are 3 possible ways here:</p> <p>1/ Is the code you see above. This does it all in MySQL, and the LAST_INSERT_ID in the second statement will automatically be the value of the autoincrement-column that was inserted in the first statement.</p> <p>Unfortunately, when the second statement itself inserts rows in a table with an auto-increment column, the LAST_INSERT_ID will be updated to that of table 2, and not table 1. If you still need that of table 1 afterwards, we will have to store it in a variable. This leads us to ways 2 and 3:</p> <p>2/ Will stock the LAST_INSERT_ID in a MySQL variable:</p> <p>A/ INSERT B/ SELECT LAST_INSERT_ID into @mysql_variable_here C/ INSERT INTO table2 (@mysql_variable_here D/ INSERT INTO table3 (@mysql_variable_here ...</p> <p>3/ Will stock the LAST_INSERT_ID in a php variable (or any language that can connect to a database, of your choice):</p> <p>A/ INSERT B/ Use your language to retrieve the LAST_INSERT_ID, either by executing that literal statement in MySQL, or using for example php's mysql_insert_id() which does that for you C/ INSERT ()</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload