我想学习如何使用MYSQL TRANSACTIONS。
我有一个用例,我有两张桌子。比方说表1和表2。现在我在表1中插入一些数据,从该表中获得的insert id
我想将其插入表2中。
如果在Table1中成功插入了值,并且在插入Table2值的过程中,如果发生任何错误,我也想从Table1中删除这些值,因为对我的Table2的查询不成功。
我只是想了解如何使用Codeigniter来完成这项工作。如何根据需要进行COMMIT或ROLLBACK。
请帮我理解一些示例代码。
更新
我还参考了Codeigniter用户指南。但我不理解Running Transactions manually
的概念,这意味着什么?如上所述,我想做一些类似触发器的自动操作,我的意思是,如果我的查询失败,我希望它使用Codeigniter回滚它所做的一切。
代码:
$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();
开始交易。
2.执行查询。
3.使用$this->db->trans_status()
检查事务状态。
4.如果status
是使用$this->db->trans_commit();
的真commit
事务。
5.如果status
为假,则使用$this->db->trans_rollback();
的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