0

我有一个$db在 mysqli 下列出的数据库。该数据库包含两个表,我在下面将它们列为tabletable2(仅用于此示例)。表 2 的行需要表中的 id。这很好,但是将列添加到 table2 中可能会出现问题,因此需要回滚例程。但是,它似乎不起作用。

我从关闭自动提交开始。然后我尝试输入回滚命令,即使我正在使用该die命令表示失败。就我而言,交易可能会在运行中被遗忘,并且数据库应该仍然稳定。所以我不确定这里发生了什么,除非数据库完全忽略了我试图关闭自动提交的事实。

我的代码的基本结构如下:

function problem($str)
{
    global $db;
    mysqli_rollback($db);
    die($str);
}

mysqli_autocommit($db,false);

//Basic check if exists
$sqlstr = "SELECT * FROM table WHERE name = '$name';";
$r = mysqli_query($db,$sqlstr);
if (mysqli_num_rows($r)>0){problem("A row already exists under that id");}

//Insert the row
$sqlstr = "INSERT INTO table (name,v1,v2,v3) VALUES ('$name','$v1','$v2','$v3');";
$r = mysqli_query($db,$sqlstr);
if (!$r){problem("Could not insert into the table. $sqlstr");}

//Get the generated id part 1
$sqlstr = "SELECT id FROM table WHERE name = '$name';";
$r = mysqli_query($db,$sqlstr);
if (!$r){problem("Could not add into the table. $sqlstr");}

//Get the generated id part 2
$row = mysqli_fetch_assoc($r);
$eid = $row['id'];

//A simple loop
$count = count($questions);
for ($i=1;i<=$count;$i++)
{
    //This is where it typically could die.
    $r = mysqli_query($db,"INSERT INTO table2 VALUES (...);");
    if (!$r){problem("Could not add to the table2. $sqlstr");}
}

mysqli_commit($db);

有什么我想念的吗?我试图尽可能地遵循我为自动提交找到的示例。

4

1 回答 1

1

事务只有在表引擎支持时才起作用,例如 InnoDB。

于 2012-04-25T01:29:57.487 回答