The U of CRUD represents the process to update data record(s) from a database in a database. CodeIgniter uses the database function $this->db->update()
to update database records; this recipe will explain how it is done.
The following is the SQL code required to support this recipe; you'll need to adapt it to your circumstances.
CREATE TABLE IF NOT EXISTS `ch6_users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `firstname` varchar(50) NOT NULL, `lastname` varchar(50) NOT NULL, `username` varchar(20) NOT NULL, `password` varchar(20) NOT NULL, `created_date` int(11) NOT NULL, `is_active` varchar(3) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; INSERT INTO `ch6_users` (`firstname`, `lastname`, `username`, `password`, `created_date`, `is_active`) VALUES ('Jessica', 'Welsh', 'jesswelsh', 'password', 1366114115, 'yes'),
We're going to create the following two files (or amend those files if you have already created them):
/path/to/codeigniter/application/controllers/database.php
/path/to/codeigniter/application/models/database_model.php
The following step will demonstrate how to update data into a database using CodeIgniter Active Record:
/path/to/codeigniter/application/controllers/database.php
:public function update_row() { $id = 1; $data = array( 'firstname' => 'Jessica', 'lastname' => 'Welsh', 'username' => 'jesswelsh', 'password' => 'password', 'created_date' => time(), 'is_active' => 'yes' ); $this->load->model('Database_model'), $result = $this->Database_model->update_row($id, $data); redirect('database/select_row'), } Add the following code into the file: /path/to/codeigniter/application/models/database_model.php::: function update_row($id, $data) { $this->db->where('id', $id); $this->db->update('ch6_users', $data); } array(1) { [0]=> object(stdClass)#20 (7) { ["id"]=> string(1) "1" ["firstname"]=> string(7) "Jessica" ["lastname"]=> string(5) "Welsh" ["username"]=> string(9) "jesswelsh" ["password"]=> string(8) "password" ["created_date"]=> string(10) "1366117753" ["is_active"]=> string(3) "yes" } }
In the controller we just saw, public function update_row()
assigns $id
with the value 1
—however this can be from post, get, session or another source—and loads the database model, passing the variable $id
to it as follows:
$this->load->model('Database_model'), $result = $this->Database_model->update_row($id, $data);
The model function update_row()
updates the matching record from the table as follows:
function update_row($id, $data) { $this->db->where('id', $id); $this->db->update('ch6_users', $data); }
18.117.196.184