我查了一下,看看究竟受影响的人返回了什么。如果删除了某些东西,它应该返回> 0,如果没有,则返回0,对吗?
但是当我删除产品时,它会被删除,因为它通过产品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');
}
}
返回的值始终为false,即0.但是当我检查数据库以查看产品是否已删除时,它将被删除。有人能指出我做错了什么吗?
affected_rows()仅适用于“写入”查询。
执行“写入”类型查询(插入,更新等)时,显示受影响的行数。
注意:在MySQL中,“DELETE FROM TABLE”返回0个受影响的行。数据库类有一个小的hack,允许它返回正确数量的受影响的行。默认情况下,此hack已启用,但可以在数据库驱动程序文件中将其关闭。
您可能希望确保已启用hack。 http://ellislab.com/codeigniter/user-guide/database/helpers.html
$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))
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;
}
}
试试这个:
if($this->db->delete($tableName))
return true;
else
return false;
这篇文章很老但我遇到了同样的问题。由于帖子没有“解决”并仍然相关,我添加了我的解决方案。
实际上,删除直接返回一个布尔值,所以函数delete_product
可以简化为:
function delete_product($id)
{
$tables = array('products', 'attributes');
$this->db->where('p_id', $id);
$res = $this->db->delete($tables);
return $res;
}
有一些错误
你写了:if ($this->db->affected_rows() > 0)
但它应该是:if ($this->db->affected_rows > 0)
你需要从affected_rows()中删除()并仅写入affected_rows ...