I want to implement a SQL statement using codeigniter active record.
UPDATE tags SET usage = usage+1 WHERE tag="java";
How can I implement this using Codeigniter active records?
Regards
You can use $this->db->affected_rows() in Codeigniter this returns a numeric value when doing "write" type queries (insert, update, etc.). In MySQL DELETE FROM TABLE returns 0 affected rows. The database class has a small hack that allows it to return the correct number of affected rows.
Mirov When we are working with codeigniter, the data only updated when there is some change in the input field's value and then the $this->db->affected_rows() will return value greater then 0.
CodeIgniter gives you access to a Query Builder class. This pattern allows information to be retrieved, inserted, and updated in your database with minimal scripting. In some cases only one or two lines of code are necessary to perform a database action.
Update records in Database Table with CodeIgniter. The Codeigniter allows us to perform the database action like – select, insert, update, and delete with the minimal script. The $this->db->update() method is used for update existing record.
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 – $set (array):- An associative array of column/value for update.
The Codeigniter allows us to perform the database action like – select, insert, update, and delete with the minimal script. The $this->db->update () method is used for update existing record. It takes table name and an array or object as the parameter. In the demonstration, I am listing the user’s list with the edit option.
I always use the CodeIgniter models to do all the MySQL querys (insert, select, updates...) but this won't work if you want to update a count field +1.
$this->db->set('usage', 'usage+1', FALSE);
$this->db->where('tag', 'java');
$this->db->update('tags');
You can also use something like this
$data = array('usage' => 'usage+1', *other columns*);
$this->db->where('tag', 'java');
$this->db->update('tags', $data);
UPDATE: $data was not being passed on to update
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With