gpt4 book ai didi

php - Codeigniter 事务不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 12:02:00 25 4
gpt4 key购买 nike

我有一个将行插入表格的函数,如下所示

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();

然后它将事务提交两次。

你有两个解决方案:

    $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

关于php - Codeigniter 事务不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28694685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com