CodeIgniter 4 Datatables Example

Codeigniter

Nicesnippets

31-10-2020


Hi Guys,

In this tutorial,I will learn you how to implement and use datatables in codeigniter 4.you can easy nad simply implement and use datatables in codeigniter 4.

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.

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.

Step 1: Install Codeigniter 4


Install the new Codeigniter 4 project using the composer package.

composer create-project codeigniter4/appstarter

Step 2: 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');

Step 3: Configure Database Connection

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

public $default = [

'DSN' => '',

'hostname' => 'localhost',

'username' => 'test',

'password' => '4Mu99BhzK8dr4vF1',

'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.

CREATE TABLE users (

id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',

name varchar(100) NOT NULL COMMENT 'Name',

email varchar(255) NOT NULL COMMENT 'Email Address',

PRIMARY KEY (id)

) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;

INSERT INTO `users` (`id`, `name`, `email`) VALUES

(1, 'Mehul', '[email protected]'),

(2, 'Dharmik', '[email protected]'),

(3, 'Divyesh', '[email protected]'),

(4, 'Savan', '[email protected]'),

(5, 'Rajesh', '[email protected]'),

(6, 'Piyush', '[email protected]'),

(7, 'Luther', '[email protected]'),

(8, 'Wayne Barrett', '[email protected]'),

(9, 'Vincent Ramos', '[email protected]'),

(10, 'Susan Warren', '[email protected]'),

(11, 'Jason Evans', '[email protected]'),

(12, 'Madison Simpson', '[email protected]'),

(13, 'Marvin Ortiz', '[email protected]'),

(14, 'Felecia Phillips', '[email protected]'),

(15, 'Tommy Hernandez', '[email protected]');

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.

# MAMPP

public $default = [

...

'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',

...

]

# XAMPP

public $default = [

...

'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',

...

]

Step 4: Create New Model

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

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model

{

protected $table = 'users';

protected $primaryKey = 'id';

protected $allowedFields = ['name', 'email'];

}

Step 5: Create Controller

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

<?php

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);

}

}

Step 5: 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.

app/Config/Routes.php

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

Step 6: 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.

app/Views/user_view.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 4 Datatables Example</title>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

</head>

<body>

<div class="container mt-5">

<div class="mt-3">

<table class="table table-bordered" id="users-list">

<thead>

<tr>

<th>Id</th>

<th>Name</th>

<th>Email</th>

</tr>

</thead>

<tbody>

<?php if($users): ?>

<?php foreach($users as $user): ?>

<tr>

<td><?php echo $user['id']; ?></td>

<td><?php echo $user['name']; ?></td>

<td><?php echo $user['email']; ?></td>

</tr>

<?php endforeach; ?>

<?php endif; ?>

</tbody>

</table>

</div>

</div>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">

<script type="text/javascript" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>

<script>

$(document).ready( function () {

$('#users-list').DataTable();

} );

</script>

</body>

</html>

Step 6: Run Application

Run the following command to start the app:

php spark serve

Check the app on the following URL:

http://localhost:8000/index.php/users-list

It will help you...