MySQL Insert into Multiple Tables
Attempting to insert data into multiple tables with a single MySQL query may yield unexpected results. While it may seem like multiple queries would resolve the issue, correlating the auto-increment ID from the user table to the manual user ID for the profile table presents a challenge.
Using Transactions and LAST_INSERT_ID()
To insert into multiple tables in a single transaction, use the following approach:
BEGIN; INSERT INTO users (username, password) VALUES('test', 'test'); INSERT INTO profiles (userid, bio, homepage) VALUES(LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com'); COMMIT;
Storing the Auto-Increment ID in a Variable
Alternatively, storing the auto-increment ID in a variable allows for referencing it in subsequent queries. This can be achieved using:
MySQL variable:
INSERT INTO ... SELECT LAST_INSERT_ID() INTO @mysql_variable_here; INSERT INTO table2 (@mysql_variable_here, ...);
PHP variable:
INSERT ... $result = mysql_query("SELECT LAST_INSERT_ID()"); $id = mysql_result($result, 0); INSERT INTO table2 ($id, ...);
Transaction Considerations
Regardless of the approach chosen, consider the potential impact of interrupted execution. In the absence of transactions, inconsistency may arise in your database. To prevent this, wrap the insert statements in a transaction, as demonstrated above.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3