I search through the net but i didn't find any solution, My problem is that how do I now during update that if a row values has changed or not or if a row is affected?
Asked
Active
Viewed 8,056 times
4
-
1use this : $this->db->affected_rows(); – senthilbp Jul 17 '13 at 06:58
-
That's true and probably is [the answer](http://stackoverflow.com/questions/10766031/mysql-database-update-and-codeigniter-rows-affected-function?rq=1). Just as a side-note: `affected_rows()` doesn't belong to CI Active Record, It's a part of CI SQL Drivers. – Hashem Qolami Jul 17 '13 at 07:01
3 Answers
8
use affected_rows()
;
$this->db->affected_rows()
Displays the number of affected rows, when doing "write" type queries (insert, update, etc.).

bipen
- 36,319
- 9
- 49
- 62
3
When we are working with CodeIgniter, the data is only updated when there is some change in the input field's value and then the $this->db->affected_rows()
will return a value greater than 0.
Suppose we have two fields, 'name' and 'email'. If we try to submit the form without changing any of the field, then $this->db->affected_rows()
will return 0, else it will return 1.
A better approach is to use:
if ($this->db->affected_rows() >= 0) {
return true; // your code
} else {
return false: // your code
}

Jamal
- 763
- 7
- 22
- 32

Haisum Usman
- 518
- 5
- 13
-
That information that affected_rows will only return 1 if something was changed is very important. I just had a problem with an "upsert" function that was expecting affected_rows to be 1 after the update statement if the row exists. Contrary to my expectation, if the row exists but the update tries to set it to the same values like before, then affected_rows will return 0. – webtopf Jun 13 '16 at 03:18
0
I think this is the simplest way to achieve this goal.
return ($this->db->affected_rows() != 1) ? false : true;

Mohammad Naim Dahee
- 909
- 10
- 18