2015-02-24 67 views
0

我有這將插入一行到表中的功能,類似下面笨交易不工作

function fn_insert_user() { 
    $this->db->trans_begin(); 
    $this->db->query('INSERT INTO user VALUES(9,"john", "9865321245")'); 
    $this->db->query('INSERT INTO user VALUES(8,"martin", "8865321245")'); 
    $this->db->trans_complete(); 

    if ($this->db->trans_status() === FALSE) 
    { 
     $this->db->trans_rollback(); 
     echo 'something bad happened'; 
    } 
    else 
    { 
     $this->db->trans_commit(); 
     echo 'everything is fine'; 
    } 

} 

現在主鍵8已經存在,因此預期它不應該允許插入第二個查詢(這是罰款)。

它成功地回滾第一查詢,但問題是,不是打印 '壞事發生了' 它打印

A Database Error Occurred 
Error Number: 1062 
Duplicate entry '8' for key 'PRIMARY' 
INSERT INTO user VALUES(8,"martin", "8865321245") 
Filename: C:\wamp\www\landmark\system\database\DB_driver.php 
Line Number: 330 
+0

已經enrty'8'是inserted.please檢查您的數據庫 – 2015-02-24 11:35:38

+0

截斷你的表,並與完整的新嘗試條目。 – 2015-02-24 11:39:24

+0

是的我知道,但因爲它會導致錯誤,它應該打印錯誤「發生了什麼不好的事情」,而不是通常的錯誤代碼錯誤 – D555 2015-02-24 11:39:36

回答

3

如果你

$this->db->trans_complete(); 

而且

$this->db->trans_commit(); 

然後它會提交兩次交易。

你有2個解決方案:

$this->db->trans_start(); 
    $this->db->query('QUERY'); 
    $this->db->trans_complete(); 

    if ($this->db->trans_status() === FALSE) 
    { 
     echo "fail"; 
    } 

OR

$this->db->trans_begin(); 
$this->db->query('QUERY...'); 


if ($this->db->trans_status() === FALSE) 
{ 
    $this->db->trans_rollback(); 
} 
else 
{ 
    $this->db->trans_commit(); 
} 

詳情見文件; http://www.codeigniter.com/user_guide/database/transactions.html

0

這是不是一個問題TRANSATION ...

試試:

function fn_insert_user() { 

    $this->db->trans_begin(); 
    $this->db->query('INSERT INTO user VALUES("john", "9865321245")'); 
    $this->db->query('INSERT INTO user VALUES("martin", "8865321245")'); 
    $this->db->trans_complete(); 

    if ($this->db->trans_status() === FALSE) 
    { 
     $this->db->trans_rollback(); 
     echo 'something bad happened'; 
    } 
    else 
    { 
     $this->db->trans_commit(); 
     echo 'everything is fine'; 
    } 

}