我要插入两个表
A(id,firstName, lastName)
和
B(id,来自 A 的 id,xyz)
。
如何使用事务同时插入两个表?
如果 B 没有被插入,那么也会回滚 A。你能帮帮我吗?
最佳答案
如果你沿着这条路走下去,请使用 mysql_insert_id()。
<?
mysql_query("START TRANSACTION");
$q1 = mysql_query("INSERT INTO table A (id, firstName, lastName) VALUES (?, ?, ?)");
// This is your baby. The id of the last record inserted
$last_inserted_id = mysql_insert_id();
$q2 = mysql_query("INSERT INTO table b (id, id from A, xyz) VALUES (?, ?, ?)");
// If query1 and query2 succeeded, commit changes to your database
// Creates both records
if ($q1 && $q2) {
mysql_query("COMMIT");
}
else {
// Else initiate a rollback, and no records are committed.
mysql_query("ROLLBACK");
}
?>
关于mysql - 在mysql中使用事务插入多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25281602/