Codeigniter 4 Crud Operation With source code

699 views 5:08 pm 0 Comments June 20, 2020
Best Codeigniter 4 Crud Operation

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';
To
public $baseURL = 'http://localhost/cicrud/';
//remove the index.php from indexPage
public $indexPage = '';
//change the uriProtocol
public $uriProtocol = 'REQUEST_URI';
To
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
 * --------------------------------------------------------------------
 */
$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('CodeigniterCrud');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->setAutoRoute(true);

/**
 * --------------------------------------------------------------------
 * 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_id` INT(11) NOT NULL AUTO_INCREMENT,
  `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`)
) ENGINE=INNODB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

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.

<?php
namespace App\Models;
 
use CodeIgniter\Model;
class Demo_model extends Model {
 
    var $table = 'tbl_employee';
     
    public function __construct() {
        parent::__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) {
        $this->db->table($this->table)->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();
        $id=$this->request->uri->getSegment(3);
        $btn='Save';
        if($id>0){
            $btn='Update';
        }
        $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();
        if($id>0){
        $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(); 
        $emp_id=$this->request->getPost('edit_id');
        $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'),
        );
        if($emp_id){
            $this->Demo_model->emp_update(array('emp_id' => $emp_id), $data);
            $this->session->setFlashdata('item', 'Data Updated');
        }else{
            $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']);
        $emp_id=$this->request->getPost('empid');
        $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

header.php

<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?=$title?></title>
    <meta name="description" content="<?=$desc?>"/>
    <meta name="description" content="<?=$keyword?>"/>
<meta name="robots" content="index, follow"/>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="<?=base_url()?>/assets/style.css">
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
  </head>
  <body>
  <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='https://i0.wp.com/technolila.com/wp-content/uploads/2020/01/cropped-technolila-logo-1-5.png?fit=495%2C91&ssl=1'></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>
      </button>
      <div class="collapse navbar-collapse" id="navbarResponsive">
        
      </div>
    </div>
  </nav>

crud.php 

<div class="container">
    <div class="row">
        <div class="col-lg-3">
            <h1 class="mt-5">Codeigniter 4 CRUD- Input Form </h1>
            <?php
                 $this->session = \Config\Services::session();
               
                
                if($this->session->getFlashdata('item')){
                ?>
                <div class="alert alert-success" role="alert">
  <?php  echo $this->session->getFlashdata('item');  ?>
</div>
<?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"
                                autocomplete="off">
                        </div>
                    </div>
                    <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>
                    </div>
                    <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>
                    </div>
                    <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>
                    </div>
                    <div class="form-group">
                         <input type='submit' value='<?=$btn?>' class='btn btn-primary'>
</div>
                </div>
            </form>
        </div>
        <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%">
                        <thead>
                            <tr>
                                <th>S.N<div>S.N</div></th>
                                <th>Name<div>Name</div>
                                </th>
                                <th>Address<div>Address</div>
                                </th>
                                <th>Email<div>Email</div>
                                </th>
                                <th>Phone<div>Phone</div>
                                </th>
                                <th>Action <div>Action</div>
                                    </p>
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $c=0; foreach($employee as $emp){ $c++;?>
                            <tr>
                            <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>
                                
                                <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>
                                    </form>



                                </td>
                            </tr>
                            <?php }?>



                        </tbody>

                        <tfoot>
                            <tr>
                                <td>S.N<div>S.N</div>
                                </td>
                                <td>Name<div>Name</div>
                                </td>
                                <td>Address<div>Address</div>
                                </td>
                                <td>Email<div>Email</div>
                                </td>
                                <td>Phone<div>Phone</div>
                                </td>
                                
                                <td>Action<div>Action</div>
                                </td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<style>
    .mt-5 {
    font-size: 16px !important;
    font-weight: bold;
    border-bottom: 1px solid #ccc;
}
</style>

 footer.php

 
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
 
 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
 
  
  
  
   </body>
 </html>

Run The Application

Now you can run the application by following url

1
http://localhost/cicrud/

Conclusion

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.

Tags: , , , , ,

One thought on “Codeigniter 4 Crud Operation With source code”

Leave a Reply