2
votes

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.

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. However, if I comment out the

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

It will still subtract 1 from the total_entry.

How do I fix this? Thanks.

1
shouldn't be affected rows > 0, after the deletion was made, then make the subtraction on the other table. your if condition is inverted, if affected rows == 0 (no affected rows), then make subtraction, that doesn't make sense - Kevin
@Ghost so how exactly can I fix it? - Taylor
the answer is already above, change the if condition - Kevin
@Ghost The first two words: "shouldn't be". Do you mean "It shouldn't be" or "Shouldn't it be"? - Taylor
no need to :) actually you can answer your own question, its valid here on SO, im just glad that helped - Kevin

1 Answers

0
votes

I don't know if you have fixed this yet, but I think what Ghost was saying is your

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. In CodeIgniter is says that the affected_rows() method is for "doing 'write' type queries (insert, update, etc.)".

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." 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.