如何在mysqli中开始和结束事务?

据我了解,事务开始于调用$mysqli->autocommit(FALSE);语句,然后终止于调用$mysqli->commit();命令,如下例所示。

<?php

//Start transaction

$mysqli->autocommit(FALSE);

$mysqli->query('UPDATE `table` SET `col`=2');

$mysqli->query('UPDATE `table1` SET `col1`=3;');

$mysqli->commit();

//End transaction

//Executing other queries without transaction control

$mysqli->query("Select * from table1");

$mysqli->query("Update table1 set col1=2");

//End of executing other queries without transaction control

//Start transaction

$mysqli->autocommit(FALSE);

$mysqli->query('UPDATE `table` SET `col`=2');

$mysqli->query('UPDATE `table1` SET `col1`=3;');

$mysqli->commit();

//End transaction

?>

我理解正确吗?如果不能,请指正我,因为这实际上是我第一次在现实生活中使用交易。

谢谢。

回答:

好吧,根据php doc,您是对的。

<?php

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */

if (mysqli_connect_errno()) {

printf("Connect failed: %s\n", mysqli_connect_error());

exit();

}

$mysqli->query("CREATE TABLE Language LIKE CountryLanguage");

/* set autocommit to off */

$mysqli->autocommit(FALSE);

/* Insert some values */

$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");

$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */

$mysqli->commit();

/* drop table */

$mysqli->query("DROP TABLE Language");

/* close connection */

$mysqli->close();

?>

在上面的示例中:

  • CREATE TABLE是自动提交,因为它是默认的行为。
  • INSERT INTO 自动致力于因autocommit(FALSE)
  • DROP TABLE被自动提交,因为autocommit(FALSE)复位 通过->commit();

以上是 如何在mysqli中开始和结束事务? 的全部内容, 来源链接: utcz.com/qa/407591.html

回到顶部