Home > Database > Mysql Tutorial > How to Insert Data into Multiple MySQL Tables Simultaneously?

How to Insert Data into Multiple MySQL Tables Simultaneously?

Mary-Kate Olsen
Release: 2024-12-17 11:46:25
Original
537 people have browsed it

How to Insert Data into Multiple MySQL Tables Simultaneously?

MySQL Insert into Multiple Tables: Database Normalization

Insertion of data into multiple tables simultaneously in MySQL is not directly supported. However, there are alternative approaches to achieve this functionality.

Using Transactions

To ensure data consistency across tables, it is recommended to use transactions. Transactions encapsulate a series of queries as a single unit, guaranteeing that all queries either succeed or fail together.

Here's an example using transactions:

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;
Copy after login

Retrieving the Auto-Increment Value

To insert the auto-increment id from the users table into the profiles table, you can use the LAST_INSERT_ID() function. However, if the subsequent insert statement inserts into a table with its own auto-increment column, the LAST_INSERT_ID() value will be updated to that table's value.

To preserve the original LAST_INSERT_ID() value, you can store it in a custom variable within the transaction.

Using MySQL Variables:

INSERT ...
SELECT LAST_INSERT_ID() INTO @mysql_variable_here;
INSERT INTO table2 (@mysql_variable_here, ...);
Copy after login

Using Language Variables:

// PHP example
$mysqli->query("INSERT INTO table1 ...");
$userid = $mysqli->insert_id;
$mysqli->query("INSERT INTO table2 ($userid, ...)");
Copy after login

Caution

It is important to consider database consistency when inserting into multiple tables. If interrupted, transactions ensure that all queries are either executed fully or not at all. Without transactions, partial inserts may result in inconsistencies.

The above is the detailed content of How to Insert Data into Multiple MySQL Tables Simultaneously?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template