简体   繁体   English

受影响的行不起作用-Codeigniter

[英]Affected Rows not working - Codeigniter

I have this delete function in my model. 我的模型中有此删除功能。 When you press the delete button, it will subtract the number of total notes from the total notes column in my database. 当您按下删除按钮时,它将从数据库的“总备忘”列中减去总备忘数。 For eg. 例如。 if you had 200 notes, and you deleted one of them, it will be 199 notes AND the note will be deleted from the database. 如果您有200个便笺,而您删除了其中一个便笺,那么它将是199个便笺,并且该便笺将从数据库中删除。

My code: 我的代码:

public function entry_delete($pid) {

        $uid=$this->session->userdata('uid');

        $whereConditions = array('pid' => $pid, 'uid' => $uid);
        $this->db->where($whereConditions);
        $this->db->delete('dayone_entries');

        if ($this->db->affected_rows() == 0) {
            $sql_entry = "UPDATE users set total_entry = total_entry - 1 WHERE uid = $uid";
            $this->db->query($sql_entry);
            return true;
        } else {
            return false;
}
 }

But this doesn't work. 但这是行不通的。 I don't know why but when I press the delete button from my view, it will delete it from the database AND subtract -1 from my total_entry table. 我不知道为什么,但是当我从视图中按下删除按钮时,它将从数据库中删除它,并从我的total_entry表中减去-1。 However, if I comment out the 但是,如果我注释掉

$this->db->delete('dayone_entries');

It will still subtract 1 from the total_entry. 仍然会从total_entry中减去1。

How do I fix this? 我该如何解决? Thanks. 谢谢。

I don't know if you have fixed this yet, but I think what Ghost was saying is your 我不知道您是否已解决此问题,但我认为Ghost所说的是您的问题

if ($this->db->affected_rows() == 0) {}

is doing the wrong check. 做错了检查。 If you only want it to trigger if the rows where successfully deleted you would want to check 如果只希望它成功删除行时触发,则需要检查

if ($this->db->affected_rows() > 0) {}

This is saying if the affected rows is more than 0 then do this. 这就是说如果受影响的行大于0,则执行此操作。 In CodeIgniter is says that the affected_rows() method is for "doing 'write' type queries (insert, update, etc.)". 在CodeIgniter中说, affected_rows()方法用于“执行'写入'类型查询(插入,更新等)”。

It then goes on to say "Note: In MySQL "DELETE FROM TABLE" returns 0 affected rows. The database class has a small hack that allows it to return the correct number of affected rows. By default this hack is enabled but it can be turned off in the database driver file." 然后继续说:“注意:在MySQL中,“从表删除”返回0个受影响的行。数据库类有一个小的hack,可让其返回正确数量的受影响的行。默认情况下,此hack已启用,但可以在数据库驱动程序文件中关闭。” So if your if ($this->db->affected_rows() == 0) {} is triggering in both situations then this hack could be disabled because your asking "if the affected rows equals zero do this" and it should't trigger if your delete was successful. 因此,如果您的if ($this->db->affected_rows() == 0) {}在两种情况下都被触发,则可以禁用此hack,因为您询问“受影响的行是否等于零,可以这样做”,并且不应如果删除成功,则触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM