In this tutorial you will learn about the CodeIgniter Update Query and its application with practical example.
In CodeIgniter, update() method is used to update existing record in database table. In order to generate update statement, update() method is used along with set() and where() methods in following ways –
Syntax:-
1 |
update($table = '', $set = NULL, $where = NULL, $limit = NULL) |
Here,
$table(String):- Table Name
$set(array):- An associative array of column/value for update.
$where(mixed):- It contains where clause
$limit(int):- It contains limit clause
Returns(bool):- It returns TRUE on success and FALSE on failure.
Example:- Let’s say you have a MySQL table named ’employee_master’ with the following fields –
emp_ID, emp_name, emp_email, emp_phone, emp_address, emp_code and emp_dept
Update using $this->db->update()
This is how you can update an existing record into ’employee_master’ table using $this->db->update().
1 2 3 4 5 6 7 8 9 10 |
$data = array( 'emp_code' => 'EMP10', 'emp_dept' => 'Marketing' ); $this->db->update('employee_master',$data,'emp_ID=1'); Or as an array: $this->db->update('employee_master',$data,array('emp_ID' => 1)); |
Update with $this->db->where()
This is how you can update an existing record into ’employee_master’ table using $this->db->update() along with $this->db->where().
1 2 3 4 5 6 |
$data = array( 'emp_code' => 'EMP10', 'emp_dept' => 'Marketing' ); $this->db->where('emp_ID', $id); $this->db->update('employee_master',$data); |
Update with $this->db->set()
This is how you can update an existing record into ’employee_master’ table using $this->db->update() along with $this->db->set().
1 2 3 4 5 6 7 |
$data = array( 'emp_code' => 'EMP10', 'emp_dept' => 'Marketing' ); $this->db->set($data) $this->db->where('emp_ID', $id); $this->db->update('employee_master'); |
Update using $this->db->update_batch()
This is how you can update an existing records into ’employee_master’ table using $this->db->update_batch().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
$data = array( array( 'emp_ID' => 1 , 'emp_code' => 'EMP10' , 'emp_dept' => 'Marketing' ), array( 'emp_ID' => 2 , 'emp_code' => 'EMP20' , 'emp_dept' => 'Marketing' ) ); $this->db->update_batch('employee_master', $data, 'emp_ID'); // Produces: // UPDATE `employee_master` SET `emp_code` = CASE // WHEN `emp_ID` = 1 THEN 'EMP10' // WHEN `emp_ID` = 2 THEN 'EMP20' // ELSE `emp_code` END, // `emp_dept` = CASE // WHEN `emp_ID` = 1 THEN 'Marketing' // WHEN `emp_ID` = 2 THEN 'Marketing' // ELSE `emp_dept` END // WHERE `emp_ID` IN (1,2) |
The first parameter will contain the table name, the second is an associative array of values, the third parameter is the where key.