2013-03-11 91 views
0

我檢查了一下,看看究竟是什麼affected_rows返回。它應該返回> 0,如果有東西被刪除,如果沒有東西是0,是正確的?Affected_rows總是在刪除時返回false

但是,當我刪除產品時,它將被刪除,因爲它通過產品ID存在。但是,當我想測試通過試圖做到這一點在我的模型是否有問題的產品已被刪除:

function delete_product($id) 
{ 
    $tables = array('products', 'attributes'); 
    $this->db->where('p_id', $id); 
    $this->db->delete($tables); 


    if ($this->db->affected_rows() > 0) 
    { 
     return TRUE; 
    } 
    else 
    { 
     return FALSE; 
    } 
} 

和值等返回到我的控制器:

public function delete() 
{ 
    $id = $this->uri->segment(3); 

    $this->a_model->delete_product($id); 

    if($res == FALSE) 
    { 
     $this->session->set_flashdata('success_delete', 'Product deleted successfully.'); 
     redirect('admin/index'); 
    } 
    else 
    { 
     $this->session->set_flashdata('error_delete', 'Product not deleted. We gots an issue.'); 
     redirect('admin/index'); 
    } 
} 

返回值總是錯誤的,即0。但是,當我檢查我的數據庫,看看產品是否被刪除,它會被刪除。有人能指出我做錯了什麼嗎?

+0

成交會是一個更好的方式做刪除? – a7omiton 2013-03-11 19:26:51

+0

我使用交易進行測試......它的一切都很好。 – a7omiton 2013-03-11 19:31:35

回答

2

affected_rows()僅適用於「寫入」查詢。

顯示執行「寫入」類型查詢(插入,更新等)時受影響的行數。

注意:在MySQL中,「DELETE FROM TABLE」返回0個受影響的行。數據庫類有一個小黑客,它允許它返回正確數量的受影響的行。默認情況下,此hack已啓用,但可以在數據庫驅動程序文件中關閉。

您可能想確保hack已啓用。 http://ellislab.com/codeigniter/user-guide/database/helpers.html

+0

即使對於真實的條件,這是否意味着總是0? – a7omiton 2013-03-11 19:21:37

+0

真實情況是什麼意思?什麼是真的? – 2013-03-11 19:29:43

+0

您正在使用哪個CI版本?這種黑客可能無法用於較舊的CI版本。 – Girish 2013-03-11 19:47:58

1
$this->a_model->delete_product($id); 

if($res == FALSE) 

應該是:

$res = $this->a_model->delete_product($id); 

if ($res === FALSE) 

你是不是值分配給$res,你是不是分配給的$this->a_model->delete_product($id)值的變量。在處理布爾值時,您也希望使用===進行嚴格比較,以便像最佳實踐那樣安全。

你總是可以只是這樣做太:

if (!$this->a_model->delete_product($id)) 
+0

這也適用,但我已決定使用事務處理,因爲我相信如果由於某種原因查詢最終會失敗,它將不會執行刪除操作 – a7omiton 2013-03-11 22:48:17

0

試試這個:

if($this->db->delete($tableName)) 
    return true; 
    else 
     return false; 
-1

有一些失誤

你必須寫:if ($this->db->affected_rows() > 0)

,但它應該是:if ($this->db->affected_rows > 0)

您需要從affected_rows()中刪除()並僅寫入affected_rows ...

0

該帖子很舊,但是我遇到了同樣的問題。由於該帖子沒有「解決」且仍然有針對性,因此我添加了我的解決方案。

其實,直接刪除返回一個布爾值,因此函數delete_product可以像被簡化:

function delete_product($id) 
{ 
    $tables = array('products', 'attributes'); 
    $this->db->where('p_id', $id); 
    $res = $this->db->delete($tables); 
    return $res; 
} 
1
function delete_product($id){ 
    $this->db->trans_start(); 
    $tables = array('products', 'attributes'); 
    $this->db->where('p_id', $id); 
    $this->db->delete($tables); 
    $this->db->trans_complete(); 

    if($this->db->trans_status() === FALSE){ 
    return false; 
    }else{ 
    return true; 
    } 
}