Inserting multiple tables with transaction in mysql

混江龙づ霸主 提交于 2020-01-05 17:21:48

问题


I want to insert two tables

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

How can I insert the two tables simultaneously using transaction?

And also if B is not inserted then rollback the A also. Could you please help me.


回答1:


Use mysql_insert_id() if you're going down that path.

<?
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");
}

?>


来源:https://stackoverflow.com/questions/25281602/inserting-multiple-tables-with-transaction-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!