开发者

Update using Active Record in CodeIgniter

开发者 https://www.devze.com 2023-04-09 18:41 出处:网络
I have a strange problem, maybe I just don\'t understand how Active Record works well enough, but here it is. I\'m trying to update a record with a particular id. For simplicity and testing I\'m just

I have a strange problem, maybe I just don't understand how Active Record works well enough, but here it is. I'm trying to update a record with a particular id. For simplicity and testing I'm just supplying the id directly instead of a variable.

Now, if I have understood Active Record correctly, it seems to work very differently from what I'm used to in Asp.Net where I used the Entity Framework ORM. But as far as I have understood it you can select the record first in one line and then when you run update in the next line, that particular record will be updated. At least that's how it looks in the documentation. Here's the example from the docs:

$data = array(
               'title' => $title,
               'name' => $name,
               'date' => $date
            );

$this->db->where('id', $id);
$this->db->update('mytable', $data); 

So I tried doing the same thing in my code:

        $updateData = array(
           'description' => 'My localhost'
        );

        $this->myDb->where('id', 2832);
        $this->db->update('Users', $updateData);

Well, that didn't work as expected at all! It did in fact update the database, but it updated each and every record so that all records got the description field updated to "My localhost"! Good thing I'm still just using a test database...

I saw in the docs that there was an alternative way as well, by supplying the id in the update statement:

$this->db->update('Users', $updateData, array('id' => 2832));

This worked fine, so great. But... I still want to know why the first alternative didn't work, because if I don't understand this I might make other devastating mistakes in the database...

I would really开发者_开发知识库 appreciate some clarification on how this works, and why all records got updated.


$updateData = array(
    'description' => 'My localhost'
);

$this->myDb->where('id', 2832);
$this->db->update('Users', $updateData);

This is not working because you are applying the "where" clause to $this->myDb and then calling update on $this->db. Since there are no restrictions on $this->db all records are getting updated.

Change it to:

$this->db->where('id', 2832);
$this->db->update('Users', $updateData);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号