Hey everyone , this article is about CodeIgniter 4 CRUD tutorial . We will see basic CRUD (Creat , Read , Update , Delete) operations in CodeIgniter 4 . CRUD operations are one of the most used features or operations in web application .

With the help of these operations developers can easily insert , fetch , update and delete data in database and thus managing the whole web application .

We will make a simple web application interface where we can perform CRUD operations easily .

Here we are assuming that you are familiar with CodeIgniter’s MVC architecture , so we will not explain what are models and controllers here .

We will use bootstrap framework to make our web interface faster and responsive .

Getting Started

Download CodeIgniter 4

First of all we will download CodeIgniter 4 from it’s official website . You can download directly from here : CodeIgniter 4.2.1 .

CodeIgniter is a very light weight yet effective framework so it won’t take a long time to download .

After successful download of zip file , extract the file in your working directory i.e., under htdocs folder of xampp and after extraction rename the folder to CI_crud.

Initial Setup

Before proceeding further we need to make a little changes in some files of our CodeIgniter project . So open the working folder i.e., CI_crud and navigate to app/config/App.php .

And carefully make these changes in this file .

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

After this copy the .htaccess and index.php file from public folder to root folder i.e., CI_crud and make below changes in index.php file

require FCPATH . '../app/Config/Paths.php';
to
require FCPATH . 'app/Config/Paths.php';

Database configuration

In order to communicate with database server , we need to configure database credentials in app/Config/Database.php file .

In Database.php file you need to setup database name , database username , database password and database hostname . In this application we are using MySQL database .

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

Creating Database

Now we will make a database in our phpmyadmin . So navigate to http://localhost/phpmyadmin in your browser and make a database there with name ci_crud .

After creating the database run the below query to create table and insert data into it.

CREATE TABLE `users` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(100) DEFAULT NULL,
  `email` VARCHAR(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

-- to insert dummy data run below query
INSERT INTO `users` (`id`, `username`, `email`) VALUES
(1, 'hello', '[email protected]'),
(2, 'nice', '[email protected]'),
(3, 'great', '[email protected]'),
(4, 'There', '[email protected]');

Creating Routes

Now we will make routes of our application to make GET and POST request for fetching and saving the data . So open app/Config/Routes.php and add the below code inside it .

$routes->get('/', 'Home::index');
$routes->post('/saveUser', 'Home::saveUser');
$routes->post('/updateUser', 'Home::updateUser');
$routes->get('/getSingleUser/(:num)', 'Home::getSingleUser/$1');
$routes->post('/deleteUser/(:num)', 'Home::deleteUser/$1');
$routes->post('/deleteMultiUser', 'Home::deleteMultiUser/$1');

Create Model and Controller

Create Model

As you all know that models is used to make interaction with a particular table in database .

Go to app/Models directory and make a new file UserModel.php and copy the below code into it .

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $DBGroup          = 'default';
    protected $table            = 'users';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $insertID         = 0;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = ['username','email'];

    // Dates
    protected $useTimestamps = false;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];
}

Create Controller

Now it’s time to create controller so that we can check for routes and render data accordingly .

Go to app/Controllers folder and make a new file Home.php and copy the below code into it .

<?php

namespace App\Controllers;
use App\Models\UserModel;

class Home extends BaseController
{
    public function __construct()
    {
        helper(['url','form']);
        $this->user = new UserModel();

    }
    public function index()
    {
        echo view('inc/header.php');
        $data['users'] = $this->user->orderBy('id','DESC')->paginate(3);
        $data['pager'] = $this->user->pager;
        echo view('home.php',$data);
        echo view('inc/footer.php');
    }

    public function saveUser(){


        $username = $this->request->getVar("username");
        $email    = $this->request->getVar("email");

        $this->user->save(["username" => $username,"email" => $email]);

        session()->setFlashdata('success','success! registration completed');
        return redirect()->to(base_url());
    }

    public function updateUser(){
        $username = $this->request->getVar('username');
        $email = $this->request->getVar('email');
        $id = $this->request->getVar('updateId');
        $data['username'] = $username;
        $data['email'] = $email;
        $this->user->update($id,$data);
        return redirect()->to(site_url("/"));
    }

    public function getSingleUser($id){
        $data = $this->user->where('id',$id)->first();

        echo json_encode($data);
    }

    public function deleteUser($id){
        $this->user->delete($id);
        echo "deleted";
    }

    public function deleteMultiUser(){
        $ids = $this->request->getVar('ids');
        for($count = 0;$count < count($ids);$count++){
            $this->user->delete($ids[$count]);
        }
        echo "multi deleted";
    }
}

Create Views

Now it’s time to create views of our application . So we will create views in this hierarchy .

codeigniter 4 crud tutorial

header.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Codeigniter CRUD</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?display=swap&family=Roboto|Varela+Round">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="<?php echo base_url(); ?>/assets/style.css">
<script src="<?php echo base_url(); ?>/assets/main.js"></script>
</head>
<body>

footer.php

</body>
</html>

home.php


<script>
    $(document).on('click',".edit",function(e){
        // e.preventDefault();
        var els = $(this).parent().siblings();
        var id = $(this).parent().siblings()[0].value;
        $.ajax({
            url : "<?php echo base_url() ?>"+"/getSingleUser/"+id,
            method : "GET",
            success : function(data){
                var data = JSON.parse(data);
                $(".updateId").val(data['id']);
                $(".updateUsername").val(data['username']);
                $(".updateEmail").val(data['email']);
            }
        })
    })
    $(document).on('click',".delete",function(e){
        // e.preventDefault();
        var el = $(this).parent().parent();
        el.hide();
        var id = $(this).parent().siblings()[0].value;
        $.ajax({
            url : "<?php echo base_url() ?>"+"/deleteUser/"+id,
            method : "POST",
            success : function(data){
                console.log(data);
            }
        })
    })

	$(document).on("click",".delete_all_data",function(){
		var checkboxes = $(".data_checkbox:checked");
		if(checkboxes.length > 0){
			var ids = [];
			checkboxes.each(function(){
				ids.push($(this).val());
			})
			$.ajax({
				url : "<?php echo base_url() ?>"+"/deleteMultiUser",
				method : "POST",
				data : {ids : ids},
				success : function(data){
					console.log(data);
					checkboxes.each(function(){
						$(this).parent().parent().parent().hide(1000);
					})
				}
			})
		}else{
			alert("please select any data");
		}
	})
	

</script>
<div class="container-xl">
	<div class="table-responsive d-flex flex-column">
		<?php
			if(session()->getFlashdata('success')){
		?>
		<div class="alert w-50 align-self-center alert-success alert-dismissible fade show" role="alert">
			<?php echo session()->getFlashdata('success') ?>
			<button type="button" class="close" data-dismiss="alert" aria-label="Close">
			  <span aria-hidden="true">&times;</span>
			</button>
		</div>
		<?php } ?>
		<div class="table-wrapper">
			<div class="table-title">
				<div class="row">
					<div class="col-sm-6">
						<h2>CodeIgniter 4 <b>CRUD</b></h2>
					</div>
					<div class="col-sm-6">
						<a href="#addEmployeeModal" class="btn btn-success" data-toggle="modal"><i class="material-icons">&#xE147;</i> <span>Add New Employee</span></a>
						<a href="#" class="delete_all_data btn btn-danger"><i class="material-icons">&#xE15C;</i> <span>Delete</span></a>						
					</div>
				</div>
			</div>
			<table class="table table-striped table-hover">
				<thead>
					<tr>
						<th>
							<span class="custom-checkbox">
								<input type="checkbox" id="selectAll">
								<label for="selectAll"></label>
							</span>
						</th>
						<th>Name</th>
						<th>Email</th>
						<th>Actions</th>
					</tr>
				</thead>
				<tbody>
                    <?php
                        if(isset($users)){
                            foreach ($users as $user) {
                    ?>
					<tr>
                        <input type="hidden" id="userId" name="id" value = "<?php echo $user['id']; ?>" >
						<td>
							<span class="custom-checkbox">
								<input type="checkbox" id="data_checkbox" class="data_checkbox" name="data_checkbox" value="<?php echo $user['id']; ?>">
								<label for="data_checkbox"></label>
							</span>
						</td>
						<td><?php echo $user['username']; ?></td>
						<td><?php echo $user['email']; ?></td>
						<td>
							<a href="#editEmployeeModal" class="edit" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i></a>
							<a href="#deleteEmployeeModal" class="delete" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Delete">&#xE872;</i></a>
						</td>
					</tr>
                    <?php } } ?>
				</tbody>
			</table>
			<div class="d-flex justify-content-center align-items-center">
				<ul class="pagination">
					<?= $pager->links(); ?>
				</ul>
			</div>
		</div>
	</div>        
</div>
<!-- Add Modal HTML -->
<div id="addEmployeeModal" class="modal fade">
	<div class="modal-dialog">
		<div class="modal-content">
			<form action = "<?php echo base_url(); ?>/saveUser" method = "POST" >
				<div class="modal-header">						
					<h4 class="modal-title">Add Employee</h4>
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
				</div>
				<div class="modal-body">					
					<div class="form-group">
						<label>Name</label>
						<input type="text" class="form-control" name="username" required>
					</div>
					<div class="form-group">
						<label>Email</label>
						<input type="email" class="form-control" name="email" required>
					</div>				
				</div>
				<div class="modal-footer">
					<input type="button" class="btn btn-default" name="submit" data-dismiss="modal" value="Cancel">
					<input type="submit" class="btn btn-success" value="Add">
				</div>
			</form>
		</div>
	</div>
</div>
<!-- Edit Modal HTML -->
<div id="editEmployeeModal" class="modal fade">
	<div class="modal-dialog">
		<div class="modal-content">
			<form action = "<?php echo base_url() ?>/updateUser" method = "POST">
				<div class="modal-header">						
					<h4 class="modal-title">Edit Employee</h4>
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
				</div>
				<div class="modal-body">
                    <input type="hidden" name="updateId" class = "updateId" >					
					<div class="form-group">
						<label>Name</label>
						<input type="text" class="form-control updateUsername" name = "username" required>
					</div>
					<div class="form-group">
						<label>email</label>
						<input type="text" class="form-control updateEmail" name = "email"  required>
                    </div>			
				</div>
				<div class="modal-footer">
					<input type="button" name = "submit" class="btn btn-default" data-dismiss="modal" value="Cancel">
					<input type="submit" class="btn btn-info" value="Save">
				</div>
			</form>
		</div>
	</div>
</div>

Running Application

Now it’s time to run the application . Go to your browser and type the this url http://localhost/CI_crud . You will see an interface like the below image where you can perform CRUD operations easily .

codeigniter 4 crud tutorial

So that’s all for this aritcle guys . You can

Follow me on Linkedin : Anand Raj

Follow our Linkedin page : Be Practical

Join Our Telegram community over here

Checkout our latest course on udemy

codeigniter 4 crud tutorial

Chat Application with Javascript , Jquery and Firebase

Rating : 4.8

2.5 Total Hours | 27 Lectures | Intermediate

Next Article : Easiest way to connect database with javascript : 3 simple steps

Thanks for reading ✌