在mysql中插入带有事务的多个表

时间:2014-08-13 08:34:21

标签: mysql transactions sql-insert

我想插入两张表

A(id,firstName, lastName)B(id, id from A, xyz)

如何使用交易

同时插入两个表同时

如果没有插入B,那么回滚也是A.你能帮我吗?

1 个答案:

答案 0 :(得分:1)

如果您沿着那条路走下去,请使用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");
}

?>