2009-12-24 89 views

回答

0

一般而言,如果事務失敗,您應該期望從數據庫返回錯誤,就像您嘗試執行單個查詢一樣。

請注意,並非所有MySQL表類型都支持事務。

1

檢查結果(mysql_query, PHP Manual):

對於SELECT,SHOW,描述,解釋等語句返回的結果集,請求mysql_query()成功返回的資源,或者在錯誤FALSE。

對於其他類型的SQL語句,INSERT,UPDATE,DELETE,DROP等,mysql_query()在成功時返回TRUE或在錯誤時返回FALSE。

例(PHP4風格):編輯:每約翰內斯的評論

mysql_connect("localhost", "username", "password") or die(mysql_error()); 

mysql_select_db("test") or die(mysql_error()); 

$query = "INSERT INTO ..."; //Query here 

mysql_query("BEGIN"); // transaction begins 

$result = mysql_query($query); 

if(!$result) 
{ 
    mysql_query("ROLLBACK"); //Transaction rolls back 
    echo "Rolled Back."; 
    exit; 
} 
else 
{ 
    $committed = mysql_query("COMMIT"); //Commit Transaction 
    if(!$committed) 
    { 
     //Commit Failed, take appropriate action 
    } 
    else 
    { 
     echo "Successful Insert."; 
    } 
} 

或者,PDO使用改進的示例,請參閱PDO try-catch usage in functions

+0

不要使用@ operatorin這樣的過度方式。這使得調試非常困難。相反,將display_errors設置爲關閉並將錯誤記錄到日誌文件。 並且您不檢查提交是否成功... – johannes 2009-12-24 09:21:50

+0

好點 - 請參閱上面的編輯 – micahwittman 2009-12-24 09:31:30

相關問題