How to Implement and Use DataTables in CodeIgniter 4

Last Updated on by in CodeIgniter

In this tutorial, we are going to throw light on how to use and implement the DataTables in Codeigniter 4 from scratch.We will learn how to create a basic Codeigniter application with robust Implementation of DataTables in Codeigniter.

We will render the data from the database and display that data using the jQuery DataTables plugin.

Implement and Use Datatables in CodeIgniter 4

Codeigniter DataTables Example

Datatables is a widely used and most popular JavaScript library to display data in a tabular form.

It lets you add advanced interaction controls to your HTML tables and comes with built-in functionalities such as Data Sorting, Searching, Pagination, and Filtering.

To make you understand the entire process, i will be explaining everything, respectively, and gradually. Then you will comprehend every foundational step more precisely and refrain your time from being decimated from reckless mistakes.

CodeIgniter 4 Server-Side DataTables with Pagination Example

  • Step 1: Install Codeigniter
  • Step 2: Display Errors
  • Step 3: Configure Database Connection
  • Step 4: Create New Model
  • Step 5: Create Controller
  • Step 6: Create Routes
  • Step 7: Show Data List & Delete

Install Codeigniter 4

Install the new Codeigniter 4 project using the composer package.

composer create-project codeigniter4/appstarter

After installing the starter template rename the application folder as i have changed it to codeigniter-datatables-example.

Thereafter, head over to the project directory.

cd codeigniter-datatables-example

Click on the given link to manually download the Codeigniter 4 application.

Display Errors in Codeigniter

This step explains how to enable the error reporting in Codeigniter and shows errors in debugging the app in real-time.

Go to app/Config/Boot/development.php file and set the display_errors to 1 instead of 0. Perform the same process in app/Config/Boot/production.php file as well.

ini_set('display_errors', '1');

Configure Database Connection

Let’s evoke the consensus between Codeigniter and MySQL database. Open PHPMyAdmin and create `demo` database, create a username `test` along with a secure password.

Then, add your database name, username and password in app/config/database.php file and establish the database connection.

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

To save your time you can execute the SQL query from PHPMyAdmin to create the users table and insert some random data into it.

    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    user_name varchar(150) NOT NULL COMMENT 'name',
    user_email varchar(255) NOT NULL COMMENT 'email',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;

INSERT INTO `users` (`id`, `user_name`, `user_email`) VALUES
(1, 'Paul Bettany', ''),
(2, 'Vanya', ''),
(3, 'Luther', ''),
(4, 'John Doe', ''),
(5, 'Paul Bettany', ''),
(6, 'Vanya', ''),
(7, 'Luther', ''),
(8, 'Wayne Barrett', ''),
(9, 'Vincent Ramos', ''),
(10, 'Susan Warren', ''),
(11, 'Jason Evans', ''),
(12, 'Madison Simpson', ''),
(13, 'Marvin Ortiz', ''),
(14, 'Felecia Phillips', ''),
(15, 'Tommy Hernandez', '');

CodeIgniter\Database\Exceptions\DatabaseException #8
Unable to connect database : Codeigniter

If anyhow you get the Codeigniter – cannot connect to MySQL database error, then change the hostname value based on your local server e.g MAMPP or XAMPP.

public $default = [
     'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',

public $default = [
     'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',

Create New Model

Create a UserModel.php file in the app/Models/ diretory, then add the given below code.

namespace App\Models;
use CodeIgniter\Model;

class UserModel extends Model
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['user_name', 'user_email'];

Codeigniter offers various configuration options to deal with Model values, you can check the documentation here.

Create Controller

Create the app/Controllers/DatatableController.php file and add the given below code in it.

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

class DatatableController extends Controller
    // Show users list
    public function index(){
        $userModel = new UserModel();
        $data['users'] = $userModel->orderBy('id', 'DESC')->findAll();
        return view('user_view', $data);

Create Routes

Ideally, we need to create a route that will be using to display the users list within the Datatables. To generate the routes add the following code inside the app/Config/Routes.php file.

$routes->get('users-list', 'DatatableController::index');

Display Datatables in Codeigniter

In this step, we will render the data from database and display in Codeigniter template using DataTables. We have included the Datatables CDN link of jQuery and CSS in the footer.

Create app/Views/user_view.php file and insert the following code in it.

<!doctype html>
<html lang="en">

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Codeigniter 4 Datatables Example -</title>
    <link href="" rel="stylesheet">


    <div class="container mt-5">
        <div class="mt-3">
            <table class="table table-bordered" id="users-list">
                    <?php if ($users): ?>
                        <?php foreach ($users as $user): ?>
                                    <?php echo $user['id']; ?>
                                    <?php echo $user['user_name']; ?>
                                    <?php echo $user['user_email']; ?>
                        <?php endforeach; ?>
                    <?php endif; ?>

    <script src=""></script>
    <link rel="stylesheet" type="text/css" href="">
    <script type="text/javascript" src=""></script>
        $(document).ready(function () {


Run Application

Run the following command to start the app:

php spark serve

Check the app on the following URL:


JavaScript Datatables in CodeIgniter


Finally, we have completed Datatables in the Codeigniter tutorial. We have assorted everything accordingly. Now you can quickly sort, search, paginate, and filter data in Codeigniter.

Simultaneously, we have looked into every imperative and gave precedence to our main topic that is almost and equally important for every web developer.


Digamber - Author

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.