[英]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.