이것이 "php mysql transaction"에 대한 Google의 첫 번째 결과이므로, 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");