简体   繁体   English

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

[英]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 您要START TRANSACTION ,执行两次插入,然后执行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: 使用PHP和mysqli,您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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