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.
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3