How To Insert Records Using Codeigniter

To insert a record in the database using CodeIgniter, you can follow the below steps,

Load the database library

Before inserting records into a database, you need to load the database library in your CodeIgniter application. You can do this by adding the following line to your controller or model:

$this->load->database();

Prepare the data array

Next, you must prepare the data you want to insert into the database. This can be done by creating an array with the data you want to insert. For example:

$data = [
    'name' => 'Rohan',
    'email' => '[email protected]',
    'phone' => '1234567890',
    'created_at' => date('Y-m-d H:i:s')
];

Insert the data

Once you have prepared the data array, insert it into the database using CodeIgniter's insert() method. The insert() method takes two parameters: the name of the table you want to insert the data into and the data you want to insert. For example:

$this->db->insert('users', $data);

Check for errors

if ($this->db->affectedRows() > 0) {
    echo 'Insert successful';
} else {
    echo 'Insert failed';
}

That's it! You have now inserted records into a database using CodeIgniter.