How to insert data in codeigniter

For creating table the SQL query is:

CREATE TABLE demo (
  `id` int(11) NOT NULL  AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `email` varchar(30) NOT NULL,
  `password` varchar(30) NOT NULL,
   PRIMARY KEY (id)
);

Create a view file insert.php and save the below code it in application/views/insert.php.

<!DOCTYPE html>
<html>
<head>
<title>Insertdata form</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-lg-6">
                <form action="<?= base_url('demo/save') ?>" method="post">
                    <label>Name</label>
                    <input type="text" name="name" class="form-control" placeholder="Enter your name">
                    <br/>
                    
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" placeholder="Enter your email">
                    <br/>
                    
                    <label>Password</label>
                    <input type="text" name="password" class="form-control" placeholder="Enter your password">
                    <br/>
                    
                    <input type="submit" value="Insertdata" class="form-control">
                </form>
            </div>
        </div>
    </div>
</body>
</html>

Create a controller file Demo.php and save it in application/controller/Demo.php.

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

class Demo extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model("Demo_Model");
    }
    function insert(){
        $this->load->view("insert");
    }
    
    function save(){
        $data = $this->input->post();
        $result = $this->Demo_Model->save("demo",$data);
        if (!empty($result)){
            redirect(base_url("demo/insert"));
        }
    }
}
   

Create a model file Demo.php and save it in application/models/Demo_Model.php.

<?php

class Demo_Model extends CI_Model{
    
    function save($table_name,$data){
        $this->db->insert($table_name,$data);
        return $this->db->insert_id();
    }
}

Let us execute this example by the following URL in the browser. This URL may be different based on your website.

https://howtowebcode.com/demo/insert