How to insert a record into the Database using CodeIgniter

To insert a record into a database using the CodeIgniter PHP framework, follow these steps:

Step 1: Set Up CodeIgniter

Make sure you have CodeIgniter installed and configured correctly. You should have your database settings configured in the application/config/database.php file.

Step 2: Create a Model

CodeIgniter follows the MVC (Model-View-Controller) pattern. You should create a model to handle database interactions. Create a new PHP file in the application/models directory, for example, MyModel.php. Here's a basic model structure:

class MyModel extends CI_Model {
    public function __construct() {
        $this->load->database(); // Load the database library

    public function insert_data($data) {
        $this->db->insert('your_table_name', $data); // Replace 'your_table_name' with your actual table name
        return $this->db->insert_id(); // Return the ID of the inserted record

Step 3: Create a Controller

Create a controller to handle the insertion logic. Create a new PHP file in the application/controllers directory, for example, MyController.php. Here's a basic controller structure:

class MyController extends CI_Controller {
    public function __construct() {
        $this->load->model('MyModel'); // Load the model

    public function insert_data() {
        // Prepare the data you want to insert
        $data = array(
            'column1' => 'value1',
            'column2' => 'value2',
            // Add more columns and values as needed

        // Call the model's insert_data method to insert the record
        $inserted_id = $this->MyModel->insert_data($data);

        if ($inserted_id) {
            echo "Record inserted with ID: " . $inserted_id;
        } else {
            echo "Insertion failed.";

Step 4: Create a Route

Configure a route in application/config/routes.php to map a URL to your controller method. For example:

$route['mycontroller/insert'] = 'MyController/insert_data';

This allows you to access the insertion logic via a URL like

Step 5: Access the Insertion Function

Visit the URL you defined in the route to access the insertion function. The record should be inserted into the database, and you'll see a message indicating success or failure.

That's it! You've successfully inserted a record into a database using CodeIgniter. Remember to replace 'your_table_name', 'column1', 'column2', and the values with your actual table name, column names, and data to be inserted.

Muhammad Alfaiz
Alfaiz 3 months ago
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x