[英]how to use transactions in codeigniter for commit and rollback based on data change?
我想学习如何使用MYSQL TRANSACTIONS 。
我有用例,我有两张桌子。 让我们说Table1和Table2。 现在我在Table1中插入一些数据,并从该表中获取insert id
,我想将其插入表2中。
如果在Table1中成功插入值,并且在插入Table2值期间发生任何错误,我也想删除Table1中的值,因为我的Table2的查询不成功。
我只想了解如何使用Codeigniter完成此操作。 如何根据需要进行COMMIT或ROLLBACK。
请帮我一些示例代码来理解。
更新
我还提到了Codeigniter UserGuide。 但我没有理解Running Transactions manually
的概念这是什么意思? 如上所述,我想做一些像触发器这样是自动的,我的意思是如果我的查询失败,我希望它使用Codeigniter进行ROLLBACK。
码:
$this->db->trans_begin();
$data = $this->Product_m->array_from_post(array('name','description'));
$this->Product_m->save($data,$id);
$pid = $this->db->insert_id();
$num_of_license = $_POST['license'];
$this->Product_m->create_product($pid,$num_of_license);
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
else
{
$this->db->trans_commit();
}
现在在这种情况下我尝试这样做:
此语句$this->Product_m->create_product($pid,$num_of_license);
基于先前的save()方法插入数据,现在假设在create_product()方法期间发生了一些错误。 然后我想回滚。 我想删除save()方法所做的记录。
使用以下步骤。
1.使用$this->db->trans_begin();
开始你的交易$this->db->trans_begin();
。
2.执行查询。
3.使用$this->db->trans_status()
检查交易状态。
4.如果status
是真正的commit
使用事务$this->db->trans_commit();
。
5.如果status
为false,则rollback
事务使用$this->db->trans_rollback();
。
$this->db->trans_begin();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
else
{
$this->db->trans_commit();
}
有关更多信息,请参阅文档Codeigniter Transaction
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.