简体   繁体   中英

Insert information in two tables with one mysql query in PHP

I am integrating my website with a forum. So basically when a users registers through my main website, i must insert the account information in my users table and the forum's users table. However there is a slight chance, that the first query may fail, thus leaving one table empty of information, while the other has it.

If i can insert the information in both tables with one query, should it fail nothing will be added to the DB

Read up on transactions. You want to START TRANSACTION , do two INSERTs, and the COMMIT

Databases know the concept of transactions for such problems.

You encapsulate multiple database statements within a transaction and either all statements are successfull or all actions are rolled back to the previous state.

With PHP and mysqli you can do something like this:

$conn = new mysqli("localhost", "my_user", "my_password", "my_db");

//  turn off autocommit = beginn a transaction
$conn->autocommit(false);

// your db actions: multiple inserts ... what you want
$mysqli->query("insert into table1....");
$mysqli->query("insert into table2....");

// commit all changes and close connection
$conn->commit();
$conn->close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM