2016-03-27 80 views
0

我似乎遇到了PHP7中的回滾功能問題。這裏是我的代碼,但是如果我提供查詢並將錯誤放入其中,那麼它將不會回滾。它仍然承諾已經完成的一切。如何使用MySQLi事務回滾和提交?

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; 
} 
+1

能夠提交和回滾,你必須做查詢前開始交易 – num8er

回答

2

你必須在做這件事之前開始交易。

因爲您必須告訴數據庫您要開始交易。

您必須在自動提交(FALSE)後輸入:$db->begin_transaction();;

請閱讀文檔:mysqli::begin_transaction



附:請記住,不能使用引擎不支持事務的表。因此,如果在添加begin_transaction語句rollback()後無效,請檢查您的表格引擎是否已將其設置爲具有事務支持的引擎。

要檢查你的表引擎調用查詢在MySQL終端:

SHOW TABLE STATUS FROM database_name_goes_here; 

你會得到表的列表中你的數據庫定義的引擎。

要在MySQL的終端呼叫查詢得到的交易安全引擎,你可以做的名單(發現交易:YES):

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 
... 
+0

完美,感謝您的協助! – DugoutSoccer

+0

不客氣(: – num8er