MySQLi事务是如何工作的


How do MySQLi transactions work?

好吧,假设我们有多个用户。

在每次会话启动时,执行CCD_ 1。因此,每个用户都有自己到数据库的(?)连接。

其中一个用户触发了一个操作,其中应该执行对DB的原子查询。PHP提供类似的功能

$db = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
/* ATOMIC_BEGIN */
mysqli_autocommit($db, false);
mysqli_query($db, "BLAH1");
mysqli_query($db, "BLAH2");
mysqli_commit($db);
mysqli_autocommit($db, true);
/* ATOMIC_END */
mysqli_close($db);

好吧,这似乎很简单。然而,

要确定自动提交的当前状态,请使用SQL命令SELECT@@autocommit

确定autocommit mode的方法是SQL命令。mysqli_autocommit似乎不是应用于特定用户的连接,而是应用于整个数据库状态。因此交易可以如下

$db = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
// This one is on the another thread or whatever
// Runned by another user
$db2 = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
/* ATOMIC_BEGIN */
mysqli_autocommit($db, false);
mysqli_query($db, "BLAH1");
// This one is on the another thread or whatever
// Runned by another user
// Not autocommitted since we turned it off
// Can be rolled back
mysqli_query($db2, "QUERY FOR THE ANOTHER USER WHICH BREAKS OUR ATOMICITY AND RESULTS OF THE BLAH2 (E. G. LOGIN)");
mysqli_query($db, "BLAH2");
// Commits both $db and $db2 queries
mysqli_commit($db);
mysqli_autocommit($db, true);
/* ATOMIC_END */
mysqli_close($db);

这是错误的,完全没有意义:其他用户只有在mysqli_commit操作之后才会登录/注册。

我想知道隔离用户之间原子事务的正确方法,或者我在思想上犯的错误。我的目标是在ATOMIC部分之后执行$db2查询。

mysqli_autocommit只影响当前$link,不应干扰其他连接/线程。

您称之为$db的东西实际上是一个MySQLi链接资源