Codeigniter Update() Replace() and Set() Database Tutorial
In our previous tutorial parts we learned about select() and the insert() methods of codeigniter, but with them we need to do other methods of CRUD in our application. In this tutorial part 3 we will learn about the various methods of update operations possible with codeigniter.
Codeigniter Database Tutorial Part-2 Inserting Data With Codeigniter
Updating Database With Codeigniter “$this->db->update()”
Suppose your application user just changed his username and you need the changed username to be updated on his database row, at every such occasion you will need to do an update, codeigniter update() method allows you to update your database whenever you need. Update function can also be used with where function. Following is example how you can use update function.
Create new array with field name as key and the values will be new value.
Now we will pass the array to update a user’s values
$this->db->where('id', 'id of the user');
This will update the user details with new username and password where “id” is the id of that user.
Before update() method
Update() method model
Results after update()
Building Codeigniter Query With set() method “$this->db->set()”
The codeigniter set() function allows let you build query in parts rather passing it directly in array. This method is useful when you need to build query in parts i.e. when you need to perform loops and build a query. The usage of set() method is given below.
The set() method can also be used with insert() and replace() method, this variable sets all fields and it values for the query methods.
Before set() method
Set() method model
Results after set() method
Codeigniter Updating Data With replace() Method “$this->db->replace()”
The codeigniter replace() method allows to do delete and update SQL queries at the same time, this method needs primary or unique keys as determining factor. This method will save your time by allowing a single method for select(), update(), insert() and delete() . The usage of replace() method is as given below
As id is our primary key we passed our id along with the array and the replace() method will find the id, replace all values with our new values provided.
Before codeigniter replace()Replace() method model
Results after replace() method
As you can see in the output, in our query we didn’t provide the user_type field and the replace() method kept user_type null. This proves that replace method has replaced all old values for that row with our new values we provided.
In next tutorial we will learn more about codeigniter where() and delete() methods Codeigniter Database Where and Delete Beginners Tutorial Part-4
If you have any suggestions or questions, let me know in the comments below or send a message from contact us page. If you liked this part of tutorial and found this helpful then share and like our page. Subscribe for notification on new tutorials.