Codeigniter 4 Crud Operation With source code

Best Codeigniter 4 Crud Operation Tutorial For Beginners
Best Codeigniter 4 Crud Operation with source codehowdy guys !!

For any programming language ,we know CRUD( insert ,read,update,delete operation) operation is essential  before learning advance.

We assume that you are familiar with CodeIgniter’s MVC structure, so We did not go into explaining the model and controller here.

Here I will explain how to create a basic CRUD Application using CodeIgniter 4 framework with example.
if you are beginner of Codeigniter 4 this post can help you to make “CodeIgniter 4 CRUD Application

CRUD is one of the most common tasks in any development to create something in the database table, update some information, read data from the table and delete information.

How to Create Responsive Multi Level Dynamic Menu In Codeigniter

In this example, I will use bootstrap library to list posts and render the forms for creating and editing data and deleting data.

Here Very simple step of CodeIgniter 4 CRUD Application-Best Codeigniter 4 Crud Operation

Download Codeigniter 4

This is first step  to start ‘CodeIgniter 4 CRUD Application -Best Codeigniter 4 Crud Operation‘.You can easily download it from here : Download Codeigniter 4.

As we know, CodeIgniter4 is very lightweight framework so it will not take long time to download.

After download successfully, extract it in your working directory where you run your PHP script i.e if you use XAMPP then extract into htdocs folder and rename folder to ‘cicrud‘.

Basic Configurations

Now , we  will change app/config/app.php file like bellow . $baseURL,$uriProtocol

public $baseURL = 'http://localhost:8080';
public $baseURL = 'http://localhost/cicrud/';
//remove the index.php from indexPage
public $indexPage = '';
//change the uriProtocol
public $uriProtocol = 'REQUEST_URI';
public $uriProtocol = 'PATH_INFO';

Route Setup

Now we will make some change in routes.php . we need to go folder location app/Config.  change routes.php  like following

<?php namespace Config;

// Create a new instance of our RouteCollection class.
$routes = Services::routes(true);

// Load the system's routing file first, so that the app and ENVIRONMENT
// can override as needed.
if (file_exists(SYSTEMPATH . 'Config/Routes.php'))
	require SYSTEMPATH . 'Config/Routes.php';

 * --------------------------------------------------------------------
 * Router Setup
 * --------------------------------------------------------------------

 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------

// We get a performance increase by specifying the default
// route since we don't have to scan directories.
$routes->get('/', 'CodeigniterCrud::index');
$routes->get('CodeigniterCrud/(:num)', 'CodeigniterCrud::index');

 * --------------------------------------------------------------------
 * Additional Routing
 * --------------------------------------------------------------------
 * There will often be times that you need additional routing and you
 * need to it be able to override any defaults in this file. Environment
 * based routes is one such time. require() additional route files here
 * to make that happen.
 * You will have access to the $routes object within that file without
 * needing to reload it.
if (file_exists(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php'))
	require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php';

Setup Database Credentials

Now ,we will  setup database configuration so we need to  open “app/Config/Database.php” folder and open database.php file some changes in this file like as hostname, database username, database password and database name according to our mysql .

public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'ci4crud',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,

Create Database With Table

In this step  , we will create database and table. So lets open phpmyadmin and create database name  ci4crud, after  creating database successfully now you can run bellow query

CREATE TABLE `tbl_employee` (
  `emp_name` VARCHAR(100) DEFAULT NULL,
  `emp_address` VARCHAR(100) DEFAULT NULL,
  `emp_mobile` VARCHAR(20) DEFAULT NULL,
  `emp_email` VARCHAR(50) DEFAULT NULL,
  PRIMARY KEY (`emp_id`)

Create Model and Controller

Create Model

In this step we will create  first Model , so we need to go folder location app/Models/  and create model name Demo_model.php and  copy following code to this model.

namespace App\Models;
use CodeIgniter\Model;
class Demo_model extends Model {
    var $table = 'tbl_employee';
    public function __construct() {
        $db = \Config\Database::connect();
        $builder = $db->table('tbl_employee');
    public function get_all() {

       $query = $this->db->query('select * from tbl_employee');
        return $query->getResult();
    public function get_by_id($id) {
      $sql = 'select * from tbl_employee where emp_id ='.$id ;
      $query =  $this->db->query($sql);
      return $query->getRow();
    public function emp_save($data) {
        $query = $this->db->table($this->table)->insert($data);
        return $this->db->insertID();
    public function emp_update($where, $data) {
        $this->db->table($this->table)->update($data, $where);
//        print_r($this->db->getLastQuery());
        return $this->db->affectedRows();
    public function emp_delete($where) {

Create Controller

Now, we create controller  ,so we go to  folder location app/Controllers and create file name CodeigniterCrud.php

and update this file by copying following code

<?php namespace App\Controllers;
 use App\Models\Demo_model;
class CodeigniterCrud extends BaseController
    //use CodeIgniter\HTTP\RequestInterface;
 //use CodeIgniter\HTTP\ResponseInterface;
 ///use CodeIgniter\Conroller;

    public function index(){
        helper(['form', 'url']);
$this->session = \Config\Services::session();
        $this->Demo_model = new Demo_model();
        $uri = new \CodeIgniter\HTTP\URI();
        $data=array('title'=>'Codeigniter 4 CRUD with bootstrap modal-datagrid','desc'=>'Codeigniter 4 CRUD with bootstrap modal-datagrid'
       ,'keyword'=>'codeigniter 4,CRUD,datagrid,bootstrap,modal','btn'=>$btn);
        $data['employee'] = $this->Demo_model->get_all();
        $data['emp'] = $this->Demo_model->get_by_id($id);
        echo  view('header', $data);
        echo view('crud', $data);
        echo view('footer', $data); 
     helper(['form', 'url']);
        $this->session = \Config\Services::session();
        $this->Demo_model = new Demo_model(); 
        $data = array(
            'emp_name' => $this->request->getPost('emp_name'),
            'emp_address' => $this->request->getPost('emp_address'),
            'emp_mobile' => $this->request->getPost('emp_mobile'),
            'emp_email' => $this->request->getPost('emp_email'),
            $this->Demo_model->emp_update(array('emp_id' => $emp_id), $data);
            $this->session->setFlashdata('item', 'Data Updated');
            $insert = $this->Demo_model->emp_save($data); 
            $this->session->setFlashdata('item', 'Data Saved');
        return redirect()->to( base_url('CodeigniterCrud') );
    public function deleteemp(){
        helper(['form', 'url']);
        $this->Demo_model = new Demo_model();
         $this->Demo_model->emp_delete(array('emp_id' => $emp_id));
    return redirect()->to( base_url('CodeigniterCrud') );


Create Views

Now in this step we will make view file , for this we need to go folder location app/Views  and create 3 files header.php,crud.php,footer.php


<!DOCTYPE html>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="<?=$desc?>"/>
    <meta name="description" content="<?=$keyword?>"/>
<meta name="robots" content="index, follow"/>
    <link rel="stylesheet" href="">
    <link rel="stylesheet" href="<?=base_url()?>/assets/style.css">
    <link href="" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top">
    <div class="container">
      <a class="navbar-brand" href="#"><img style='width:38%' src=''></a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      <div class="collapse navbar-collapse" id="navbarResponsive">


<div class="container">
    <div class="row">
        <div class="col-lg-3">
            <h1 class="mt-5">Codeigniter 4 CRUD- Input Form </h1>
                 $this->session = \Config\Services::session();
                <div class="alert alert-success" role="alert">
  <?php  echo $this->session->getFlashdata('item');  ?>
<?php }?>
            <?= \Config\Services::validation()->listErrors(); ?>
            <form action="<?=base_url()?>/CodeigniterCrud/crudsave" method="post" class="form-horizontal">
            <input type='hidden' value='<?=@$emp->emp_id?>' name='edit_id' >
                <input type="hidden" value="3" name="book_id">
                <div class="form-body">
                    <div class="form-group">
                        <label class="control-label col-md-12">Employee Name</label>
                        <div class="col-md-12">
                            <input value='<?=@$emp->emp_name?>' name="emp_name" placeholder="Employee Name" class="form-control" type="text"
                    <div class="form-group">
                        <label class="control-label col-md-12">Employee Address</label>
                        <div class="col-md-12">
                            <input value='<?=@$emp->emp_address?>' name="emp_address" placeholder="Employee Address" class="form-control" type="text">
                    <div class="form-group">
                        <label class="control-label col-md-12">Employee Mobile</label>
                        <div class="col-md-12">
                            <input value='<?=@$emp->emp_mobile?>' name="emp_mobile" placeholder="Employee Mobile" class="form-control" type="phone">

                    <div class="form-group">
                        <label class="control-label col-md-12">Employee Email</label>
                        <div class="col-md-12">
                            <input value='<?=@$emp->emp_email?>' name="emp_email" placeholder="Employee Email" class="form-control" type="email">

                    <div class="form-group">
                         <input type='submit' value='<?=$btn?>' class='btn btn-primary'>
        <div class="col-lg-9">
            <h1 class="mt-5">Codeigniter 4 CRUD-Datagrid</h1>

            <div class="anand_wrapper">
                <div class="anand_table">
                    <table id="table_id" class="table" cellspacing="0" width="100%">
                                <th>Action <div>Action</div>
                            <?php $c=0; foreach($employee as $emp){ $c++;?>
                            <td><?php echo $c;?></td>
                                <td><?php echo $emp->emp_name;?></td>
                                <td><?php echo $emp->emp_address;?></td>
                                <td><?php echo $emp->emp_email;?></td>
                                <td><?php echo $emp->emp_mobile;?></td>
                                   <a href='<?=base_url()?>/CodeigniterCrud/<?php echo $emp->emp_id?>'>
                                    <button class='btn btn-primary'>Edit</button></a>
                                    <form method='post' action='<?=base_url()?>/CodeigniterCrud/deleteemp' style='float: right;
    margin-left: 4px;'>
                                       <input type='hidden' name='empid' value='<?php echo $emp->emp_id;?>'>
                                       <button class='btn btn-danger' type='submit'>Delete</button></a>

                            <?php }?>


    .mt-5 {
    font-size: 16px !important;
    font-weight: bold;
    border-bottom: 1px solid #ccc;


<script src=""></script>
 <script src=""></script>

Run The Application

Now you can run the application by following url



in this  Codeigniter 4 Crud Operation tutorial we have learn basic CRUD  using codeigniter 4  and bootstrap . You can find demo by clicking bellow link.

Do share this Codeigniter 4 Crud Operation with others who want to Learn CRUD operation.

Thank me by sharing this article. Sharing is caring .

Codeigniter 4 Crud source code

Demo CodeIgniter 4 CRUD Application-Best Codeigniter 4 Crud Operation Tutorial For Beginners (Codeigniter4  Crud with example)

#codeigniter 4 tutorial 2020,Codeigniter 4 Crud Operation Tutorial For Beginners,Codeigniter 4 Crud Operation,Best Codeigniter 4 Crud Operation

In this tutorial, We will learn how to perform crud operation in CodeIgniter 4. Codeigniter 4 CRUD (Create Read Update Delete) Tutorial For Beginners

Do share article  and comment if you have any query.

Written By


Comments :

Leave a Reply