【问题标题】:How do MySQLi transactions work?MySQLi 事务如何工作?
【发布时间】:2013-11-19 12:20:09
【问题描述】:

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

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

其中一个用户触发了一个操作,应该执行对数据库的原子查询。 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 查询。

【问题讨论】:

    标签: php sql mysqli transactions


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢你的回答,我也是这么想的。检查当前自动提交状态的方法完全颠覆了我的想法......
    猜你喜欢
    • 2015-11-23
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 2016-11-19
    相关资源
    最近更新 更多