【问题标题】:method to find actually data deleted or not in database in codeigniter [duplicate]在codeigniter中查找数据库中实际删除或未删除的数据的方法[重复]
【发布时间】:2014-06-13 11:43:06
【问题描述】:

大家好,有什么方法可以检查数据是否真的从数据库中删除或没有在 codeigniter 中? 我有一种方法可以从我的模型中的数据库中删除数据

             $this->db->delete('product', array('category' => $id)); 

我已经在我的控制器中设置了闪存数据 数据库中的数据不会被删除,但会显示 Flash 消息。

我只需要在从数据库中实际删除时显示闪存数据。

【问题讨论】:

  • 必须有某种方法来获取受影响的行。如果为 0,则不会删除任何内容。

标签: php mysql flash codeigniter


【解决方案1】:

我更喜欢这个

在模型中,例如称为“产品”

function deleteProductBy( $id ) {
    $this->db->where( 'category', $id );
    $this->db->delete( 'product' );

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

} 

在控制器中

  if( $this->products->deleteProductBy($id) == false ){

   // fail message is sad
} 
else{
   // success message is happy
}

所以模型中的 delete 方法只返回 true 或 false ——然后在控制器中您决定如何显示结果。然后,当您显示结果的方式发生变化时 - 模型中的删除方法保持不变。当我漫无目的时,我的建议是首先检查错误情况。

【讨论】:

  • 真假颠倒。我认为必须像这样改变if ($this->db->affected_rows() == '1') {return FALSE;}else {return TRUE;}
【解决方案2】:

试试这个:

if($this->db->delete('product', array('category' => $id))) // This will return TRUE if deleted and return FALSE if it couldn't delete the row.

如果这不起作用,我建议使用这样的东西:

$this->db->delete('product', array('category' => $id));

if ($this->db->affected_rows() > 0) // affected_rows will return you the number of affected rows, so if you delete one it will return 1.
{
     // show flash message
}

【讨论】:

  • 根据 codeigniter 用户指南 $this->db->affected_rows() 仅适用于插入或更新的写入功能。所以这个函数总是为我返回 false。
【解决方案3】:

删除表中的数据后,为该类别 ID 编写一个选择查询。如果计数为零,那么将没有具有该类别 ID 的记录。否则会有一些日期与该 ID。即,未删除。

例如,

function deleterecord(){
$this->db->delete('product', array('category' => $id));
//return TRUE or redirect to controller.
}
//after the above executed call the below function.
function findrecord(){
$query = $this->db->get_where('product', array('category' => $id));
if($query -> num_rows() == 0){
$str ="There is no data";
return $str;
}
else{
$str ="There is data";
return $str;
}
}

您可以打印函数返回值来查找结果。

【讨论】:

  • 不是很聪明 imo,因为您使用全新的查询只是为了检查是否删除了某些内容..
  • 删除记录后,您必须查找数据是否存在。为此,您必须在删除查询后添加选择查询。因此,为选择查询添加附加功能。应该在删除函数之后调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-30
  • 2015-09-11
  • 1970-01-01
相关资源
最近更新 更多