티스토리 뷰

IT 이야기/프로그래밍

[PHP] commit, rollback 예제

하늘과 나b 2013. 10. 14. 22:10

PHP에서 commit와 rollback을 사용하는 예제


출처 : http://php.net/manual/en/mysqli.rollback.php

<?php

/* DB 연결 설정 */
$mysqli = new mysqli("localhost", "gugbageri", "gugbageri", "gugbageri");

/* 연결 확인 */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* disable autocommit */
$mysqli->autocommit(FALSE);

/* We just create a test table with one auto incremental primary column and a content column*/
$mysqli->query("CREATE TABLE TestTable ( `id_column` INT NOT NULL  AUTO_INCREMENT , `content` INT NOT NULL , PRIMARY KEY ( `id_column` )) ENGINE = InnoDB;");

/* commit newly created table */
$mysqli->commit();

/* we insert a row */
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");

/* we commit the inserted row */
$mysqli->commit();

/* we insert another three rows */
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");

/* we the rollback */
$mysqli->rollback();

/* we insert a row */
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");

/* we commit the inserted row */
$mysqli->commit();

if ($result = $mysqli->query("SELECT id_column FROM TestTable")) {

   while($row = $result->fetch_row()) {
      printf("Id: %d.\n", $row[0]);
   }
    /* Free result */
    $result->close();
}

/* Drop table TestTable */
$mysqli->query("DROP TABLE TestTable");

$mysqli->close();
?>


댓글