2013-07-17 58 views
0

我需要一些幫助。如何正確使用MySQL交易

我有不同的文件。例如:

  • 的index.php,news.php
  • 包括的腳本,如:facebook.php,pay.php多。

在所有頁面上(news.php除外),事務在腳本的開始處開始,並在腳本的結尾處結束。

在index.php和news.php等頁面上,我包含了pay.php。但問題是:當我訪問index.php時,事務已經開始,所以現在有兩個事務處於活動狀態!但是我無法從pay.php中刪除交易 - 開始,因爲如果我從news.php調用腳本,則沒有活動交易。

(我的網站更復雜,有更多的頁面和東西)。

有人可以幫我嗎?謝謝!

+0

你將需要更清楚地解釋一下。這是什麼樣的交易? –

+0

這是一個MySQL事務。像http://stackoverflow.com/questions/2708237/php-mysql-transactions-examples – Jordy

+0

@jordy以及停止:)你真的應該採用新的數據庫引擎之一...不推薦使用mysql擴展。 – Orangepill

回答

1

最好的辦法是模仿嵌套事務。 (pseduocode)

class MyMysqli { 
    protected $realDb; 
    protected $transaction_count =0; 

    public function __construct ($host, $username , $passwd, $dbname){ 
     $this->realDb = new Mysqli($host, $username, $passwd, $dbname); 
    } 
    public function __get($property){ 
     return $this->realDb->$property; 
    } 

    public function __set($property, $value){ 
     return $this->realDb->$property = $value; 
    } 

    public function __call($method, $args){ 
     return call_user_func_array(array($this->realDb, $method), $args); 
    } 

    // overload begin_transaction, commit and rollback 
    public function begin_transaction(){ 
     $this->transaction_count++; 
     if ($this->transaction_count == 1){ 
       $this->realDb->begin_transaction(); 
     } 
    } 
    public function commit(){ 
     $this->transaction_count--; 
     if($this->transaction_count == 0){ 
       $this->realDb->commit(); 
     } 
    } 

    public function rollback(){ 
     throw new Exception("Error"); 
    } 
+0

謝謝,我與OOP不太好,但如何開始交易?我可以讓MySQL的這個? (更進一步,我將整個網站更新到MySQLi/PDO) – Jordy

+0

現在是升級的好時機。但是這個概念僅僅是第一次啓動一個事務並且遞增一個變量,在提交時遞減該變量並且如果它是0則提交。 – Orangepill

+0

您的谷歌搜索'模擬mysql中的嵌套事務' – Orangepill