如何使用MySQLi事务回滚和提交


How to Rollback and Commit using MySQLi Transactions?

我似乎在PHP7中的回滚功能方面遇到了问题。这是我的代码,但如果我提供查询并在其中一个查询中输入错误,它就不会回滚。它仍然提交已完成的所有内容。

function sql_transaction(...$queries) {
    global $db;
    $success = 1;
    $db->autocommit(FALSE);
    foreach($queries as $query) {
        $result = $db->query($query);
        echo $result;
        if(!$result) {
            $success = 0;
            break;
        }
    }
    if($success == 1) {
        $db->commit();
    }else{
        $db->rollback();
    }
    $db->autocommit(TRUE);
    return $success;
}

您必须在执行此操作之前启动事务。

因为您必须告诉数据库您将要启动事务。

您必须将:$db->begin_transaction();放在自动提交之后(FALSE);

请阅读文档:mysqli::begin_transaction



附言:请记住,引擎不支持事务的表是无法做到这一点的。因此,如果在添加begin_transaction语句后rollback()不起作用,请检查Your tables engine是否设置为具有事务支持的引擎。

在mysql终端中检查您的表引擎调用查询:

SHOW TABLE STATUS FROM database_name_goes_here;

您将获得数据库中已定义引擎的表列表。

要获得事务安全引擎的列表,可以通过在mysql终端中调用查询来完成(查找事务:是):

mysql> SHOW ENGINES'G
*************************** 1. row ***************************
      Engine: PERFORMANCE_SCHEMA
     Support: YES
     Comment: Performance Schema
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 2. row ***************************
      Engine: InnoDB
     Support: DEFAULT
     Comment: Supports transactions, row-level locking, and foreign keys
Transactions: YES
          XA: YES
  Savepoints: YES
*************************** 3. row ***************************
      Engine: MRG_MYISAM
     Support: YES
     Comment: Collection of identical MyISAM tables
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 4. row ***************************
      Engine: BLACKHOLE
     Support: YES
     Comment: /dev/null storage engine (anything you write to it disappears)
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 5. row ***************************
      Engine: MyISAM
     Support: YES
     Comment: MyISAM storage engine
Transactions: NO
          XA: NO
  Savepoints: NO
...