在PHP中使用一个mysql查询在两个表中插入信息

在PHP中使用一个mysql查询在两个表中插入信息

问题描述:

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

我正在将我的网站与论坛集成。 所以基本上当用户通过我的主网站注册时,我必须在我的用户表和论坛的用户表中插入帐户信息。 但是有一点点机会,第一个查询可能会失败,从而使一个表空了信息, 而另一个有它。 p>

如果我可以使用一个查询在两个表中插入信息,如果它失败,则不会将任何内容添加到数据库中 p> div>

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();