我有一个将行插入表中的功能,如下所示

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

最佳答案

如果你这样做

$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";
    }


要么

$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

09-30 15:28
查看更多