2013-03-11 92 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; 
    } 
}