Welcome Guest, Not a member yet? Register   Sign In
Update and affected rows
#1

[eluser]sk.avenger[/eluser]
I have the problem in CI with updating table ...
Give an example

table structure "example":
Code:
+----+-------+
| id | title |
+----+-------+
|  1 |  test |
+----+-------+

model ex_model:
Code:
public function save($id,$title)
{
    $this->db->set('title', $title)->where('id', $id)->update('example');
    return $this->db->affected_rows() > 0;
}

controller ex_controller:
Code:
public function edite()
{
    $this->load->model('ex_model');

    if( ! $this->ex_model->save(1,'test'))
        show_error('affected rows return 0.');
}

During the execution of the method edite(), our controller, the method save(), models ex_model, returns 0, in consequence of that, we will see on the screen error page show_error().

Why, when in the update() is transmitted exactly the same values ​​as at the moment are in the table, affected_rows() returns 0 instead of 1??
And how to be in this situation?
#2

[eluser]CroNiX[/eluser]
Because in mysql, when you do an update it only actually performs an update if at least one fields data changes. So if you don't change values, nothing was actually updated in the db so affected rows is 0. This is standard mysql behavior and has nothing to do with CI.
#3

[eluser]sk.avenger[/eluser]
Thanks for the clarification.
It turns out that it makes no sense to return the result of update?
ie method save() can be written like this:
Code:
public function save($id,$title)
{
    $this->db->set('title', $title)->where('id', $id)->update('example');
}
#4

[eluser]CroNiX[/eluser]
Don't you still want to know whether the query was successfully executed or had an error?

Code:
return $this->db->set('title', $title)->where('id', $id)->update('example');
#5

[eluser]sk.avenger[/eluser]
Yes, thank you.




Theme © iAndrew 2016 - Forum software by © MyBB