由于这是在Google上“ php mysql transaction”的第一个结果,我想我要添加一个答案,明确说明如何使用mysqli进行此操作(作为原始作者想要的示例)。这是使用PHP / mysqli进行事务处理的简化示例:
// let's pretend that a user wants to create a new "group". we will do so
// while at the same time creating a "membership" for the group which
// consists solely of the user themselves (at first). accordingly, the group
// and membership records should be created together, or not at all.
// this sounds like a job for: TRANSACTIONS! (*cue music*)
$group_name = "The Thursday Thumpers";
$member_name = "EleventyOne";
$conn = new mysqli($db_host,$db_user,$db_passwd,$db_name); // error-check this
// note: this is meant for InnoDB tables. won't work with MyISAM tables.
try {
$conn->autocommit(FALSE); // i.e., start transaction
// assume that the TABLE groups has an auto_increment id field
$query = "INSERT INTO groups (name) ";
$query .= "VALUES ('$group_name')";
$result = $conn->query($query);
if ( !$result ) {
$result->free();
throw new Exception($conn->error);
}
$group_id = $conn->insert_id; // last auto_inc id from *this* connection
$query = "INSERT INTO group_membership (group_id,name) ";
$query .= "VALUES ('$group_id','$member_name')";
$result = $conn->query($query);
if ( !$result ) {
$result->free();
throw new Exception($conn->error);
}
// our SQL queries have been successful. commit them
// and go back to non-transaction mode.
$conn->commit();
$conn->autocommit(TRUE); // i.e., end transaction
}
catch ( Exception $e ) {
// before rolling back the transaction, you'd want
// to make sure that the exception was db-related
$conn->rollback();
$conn->autocommit(TRUE); // i.e., end transaction
}
另外,请记住,PHP 5.5具有新方法mysqli :: begin_transaction。但是,PHP团队尚未对此进行记录,并且我仍然停留在PHP 5.3中,因此无法对此发表评论。
mysql_query("BEGIN");
序列而不是序列mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");