Codeigniter update query example
Codeigniter update query: We can use Codeigniter Query builder class to update data in table. Codeigniter provides classes to interact with database. Using query builder classes you can perform update action by simply writing few lines of code. While writing any query to insert, update or delete we always need to take care about sql injection and other security things. Here in this article we are going to explain how you perform update operation on database using query builder class.
Codeigniter update query With Where Condition | Example
We will create an example to update with where condition and multiple columns.
Here is simple example to update name, email and phone number in table – my_table using where condition.
$this->db->update() is used to update data in codeigniter table.
$data = array( 'name' => $name, 'email' => $email, 'phone' => $phone ); $this->db->where('id', $id); $this->db->update('my_table', $data);
This will generate the following Query :
Codeigniter update query Where example : Output
// UPDATE my_table // SET name = '{$name}', email= '{$email}',phone = '{$phone}' // WHERE id = $id
Note : You can also pass objects instead of passing array ie. $data.
You can get more details about the query builder class in codeigniter.
Read >> Query Builder CLass
Read >> Query Builder CLass Documentaion
Return Value –
>Update query return value– You can use the below syntax to check whether update is successful or not-
if($this->db->affected_rows() > 0){ // update successful }else{ // update failed }
Multiple Where Condition
You can add multiple where condition in query simply as below-
$email = 'youremail@yopmail.com'; $id = 10; $data = array( 'name' => $name, 'phone' => $phone ); $this->db->where('id', $id); $this->db->where('email', $email); // on the same way you can add other conditions $this->db->update('my_table', $data);
Advertisements