Insert data into database using codeigniter

Post Date: October 04, 2018
Last Updated: September 25, 2026

Introduction

CodeIgniter is a lightweight PHP framework that follows the MVC (Model-View-Controller) architecture. One of the most common tasks in web application development is inserting user data into a database.

In this tutorial, you will learn how to create a simple registration form and store user information such as name, email, and mobile number into a MySQL database using CodeIgniter. We will use a Controller, View, and Model to keep the application organized and maintainable.


Prerequisites

Before proceeding, ensure that:

  • CodeIgniter is installed and configured.
  • A MySQL database connection is configured in application/config/database.php.
  • A users table exists in your database.

Sample Users Table

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100),
    mobile VARCHAR(20)
);

Application Flow

User Opens Registration Form
            │
            ▼
      Fill Details
(Name, Email, Mobile)
            │
            ▼
      Click Save Data
            │
            ▼
 Controller (Insert.php)
            │
            ▼
  Model (Insert_Model.php)
            │
            ▼
 Insert Record into Database
            │
            ▼
 Success Message Displayed

Step 1: Create Controller

Create a new file:

application/controllers/Insert.php

Add the following code:

<?php
class Insert extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        // Load database
        $this->load->database();

        // Load model
        $this->load->model('Insert_Model');
    }

    public function savedata()
    {
        // Load registration form
        $this->load->view('registration');

        if($this->input->post('save'))
        {
            $n = $this->input->post('name');
            $e = $this->input->post('email');
            $m = $this->input->post('mobile');

            $this->Insert_Model->saverecords($n, $e, $m);

            echo "Records Saved Successfully";
        }
    }
}
?>

Step 2: Create Registration View

Create a new file:

application/views/registration.php

Add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Registration Form</title>
</head>

<body>

<form method="post">

<table width="600" border="1" cellspacing="5" cellpadding="5">

<tr>
<td width="230">Enter Your Name</td>
<td width="329">
<input type="text" name="name"/>
</td>
</tr>

<tr>
<td>Enter Your Email</td>
<td>
<input type="text" name="email"/>
</td>
</tr>

<tr>
<td>Enter Your Mobile</td>
<td>
<input type="text" name="mobile"/>
</td>
</tr>

<tr>
<td colspan="2" align="center">
<input type="submit" name="save" value="Save Data"/>
</td>
</tr>

</table>

</form>

</body>
</html>

Step 3: Create Model

Create a new file:

application/models/Insert_Model.php

Add the following code:

<?php
class Insert_Model extends CI_Model
{
    function saverecords($name, $email, $mobile)
    {
        $query = "INSERT INTO users VALUES('', '$name', '$email', '$mobile')";
        $this->db->query($query);
    }
}
?>

Testing the Application

  1. Start your web server (Apache/Nginx).
  2. Open your browser.
  3. Navigate to:
http://localhost/project-name/index.php/insert/savedata
  1. Fill in the registration form.
  2. Click Save Data.
  3. Verify that the record is successfully inserted into the users table.

Security Recommendation

The above example is intended for learning purposes. In production environments, avoid using raw SQL queries because they are vulnerable to SQL Injection attacks.

Instead, use CodeIgniter’s Query Builder:

$data = array(
    'name'   => $name,
    'email'  => $email,
    'mobile' => $mobile
);

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

This approach is safer, cleaner, and easier to maintain.


Conclusion

In this tutorial, you learned how to insert data into a MySQL database using CodeIgniter’s MVC architecture. We created a controller to handle user requests, a view to display the registration form, and a model to perform database operations. While the example uses a simple SQL query for demonstration, production applications should always use CodeIgniter’s Query Builder and form validation features to improve security, reliability, and maintainability.

By following these practices, you can build secure and scalable CodeIgniter applications with clean and organized code.


Frequently Asked Questions (FAQ)

1. Why should I use a Model for database operations in CodeIgniter?

Models help separate database logic from application logic. This follows the MVC architecture and makes your code easier to maintain, test, and reuse.

2. Can I validate form fields before inserting data?

Yes. CodeIgniter provides a Form Validation Library that allows you to validate required fields, email formats, mobile numbers, and more before saving data.

3. What is the safest way to insert data into a database?

The recommended method is to use CodeIgniter’s Query Builder or Active Record methods instead of writing raw SQL queries. This helps protect against SQL Injection vulnerabilities.



Talk to our experts

Have a technology challenge or looking for the right solution for your business? Our team can help you with cloud, DevOps, development, infrastructure, design, and more. Feel free to reach out to our experts here.

admin

Our team has expertise across software and web development, WordPress, e-commerce, mobile applications, UI/UX, cloud and infrastructure, DevOps, CI/CD, API integration, security, testing, automation, and technical support. The team also works with AI-based software solutions, LLMs, AI workflows, AI agents, and intelligent application development to help businesses automate processes and build smarter digital solutions. We focus on developing, deploying, maintaining, and optimising secure, scalable, and reliable technology solutions while helping businesses adopt modern technologies and drive digital transformation.

Leave a Reply

Scroll to Top