update query in codeigniter using where condition
CodeIgniter is a popular PHP framework that provides a convenient way to interact with databases. To perform an update query with a WHERE condition in CodeIgniter, you can follow these steps:
- Load the database library:
- In your controller or model, you need to load the CodeIgniter database library using the
load
method. This allows you to establish a connection with the database and use its functions. Here's an example of how to load the database library:
php
$this->load->database();
- Build the update query:
- Use the
set
method of the database library to specify the new values you want to update. Theset
method takes an associative array, where the keys represent the column names, and the values represent the new values. Here's an example:
php
$data = array(
'column1' => 'new value 1',
'column2' => 'new value 2'
);
$this->db->set($data);
- Add the WHERE condition:
- To specify the condition for updating specific rows, you can use the
where
method of the database library. Thewhere
method takes two parameters: the column name and the value to match. Here's an example:
php
$this->db->where('column3', 'value3');
- Execute the update query:
- Finally, you can execute the update query using the
update
method of the database library. Theupdate
method takes the table name as a parameter. Here's an example:
php
$this->db->update('table_name');
Putting it all together, here's an example of an update query in CodeIgniter with a WHERE condition:
$this->load->database();
$data = array(
'column1' => 'new value 1',
'column2' => 'new value 2'
);
$this->db->set($data);
$this->db->where('column3', 'value3');
$this->db->update('table_name');
This code will update the specified columns (column1
and column2
) with the new values ('new value 1'
and 'new value 2'
) in the table ('table_name'
), where the column column3
has the value 'value3'
.