How to insert data in a table with CodeIgniter


CodeIgniter is a powerful PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications.
This snippet gives you the simple and best explanation to insert data into a MySQL table.
This process contains three major steps.
  1. View
  2. Controller
  3. Model
1. View 

demo.php (place it in your view folder)

Which is the form where you will insert data
        .container {
            width: 200px;
            height: 100px;
            padding: 200px;

        label {
            padding: 10px;

        .btn {
            float: right;
            padding: 5px;
<body class="container">
<form method='POST'>

    <input type="text" name="name"><br><br>

    <input type="text" name="number"><br><br>

 <input class="btn" type="submit" name="submitdemo" value="Submit">



Welcome.php(place it in your controller folder)
which will act as a bridge between your model and controller.

defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller
    public function demo()
        $name = $this->input->post('name');

        $number = $this->input->post('number');

        $data = array(
            'name' => $name,
            'number' => $number,

        if (isset($_POST['submitdemo'])) {
            if (($name !== '')) {
            } else {
                echo 'Please fill fields';

        $this->load->view('demo.php', $data);

3. Model
Levels.php(place it in your model folder)
Model will insert the data into table colected from form(demo.php)
through controller(Welcome.php)
class Levels extends CI_Model
    public function demo($data)
        $this->db->insert('demo', $data);
        echo 'Data inserted successfully';
Run this query to create table in your database.

`id` int(11) NOT NULL,
`name` varchar(24) NOT NULL,
`number` varchar(10) NOT NULL

No comments:

Post a Comment


php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Popular Posts