CodeIgniter 4 Server Side DataTables with Pagination Tutorial

Codeigniter DataTables integration tutorial; On a web page, there are many ways to show information simplistically. However, when it comes to displaying excessive records in a user-centric manner, then DataTable is the better choice.

In the data table, information is arranged in tabular form, which helps users visualize data effortlessly.

A data table component comes with sort, search, pagination modules which makes the data visualization easier.

In this Codeigniter 4 DataTable example, we will discover how to add datatable in Codeigniter 4 app with sorting, searching and paginating functionalities using the JavaScript DataTables library.

DataTables categorizes the information in a row and column format; a user’s view can easily scan data in tabular format.

You can insert data statically or dynamically. Subsequently, in this guide, we will show you how to implement datatables in the Codeigniter app and render the data dynamically in the DataTable using the MySQL database.

CodeIgniter 4 Server-side Datatable Example

  • Step 1: Download Codeigniter App
  • Step 2: Create and Add Records in Table
  • Step 3: Create Database Connection
  • Step 4: Setting Up Model
  • Step 5: Define Logic in Controller
  • Step 6: Register or Add Routes
  • Step 7: Integrate DataTable in CI View
  • Step 8: Invoke App in Browser

Download Codeigniter App

We will create the list of the users and fetch the data dynamically from the database and represent the data on the frontend using the datatable widget.

On the console screen, type command and hit enter to download the Codeigniter app.

composer create-project codeigniter4/appstarter

Also, you may install Codeigniter app manually from the website.

Create and Add Records in Table

Use provided SQL query to generate users table and dump the fake data into the users’ table.

--
-- Table structure for `users` table 
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL COMMENT 'Primary Key',
  `name` varchar(100) NOT NULL COMMENT 'name',
  `email` varchar(100) NOT NULL COMMENT 'email',
  `phone` varchar(100) NOT NULL COMMENT 'phone'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='users list';

--
-- Dumping data in `users` table
--

INSERT INTO `users` (`id`, `name`, `email`, `phone`) VALUES
(1, 'Elizabeth', ' alfreda1@hotmail.com', ' 803-332-6744'),
(2, 'Maria Nave', ' immanuel@gmail.com', ' 743-230-1388'),
(3, 'Elvia Nunez', ' alvena1@gmail.com', ' 307-616-3700'),
(4, 'Lucille Saucedo', ' valentin@gmail.com', ' 223-414-1964'),
(5, 'Billy Jankowski', ' reva@gmail.com', ' 546-398-7344'),
(6, 'Elizabeth', ' alfreda1@hotmail.com', ' 803-332-6744'),
(7, 'Maria Nave', ' immanuel@gmail.com', ' 743-230-1388'),
(8, 'Elvia Nunez', ' alvena1@gmail.com', ' 307-616-3700'),
(9, 'Lucille Saucedo', ' valentin@gmail.com', ' 223-414-1964'),
(10, 'Billy Jankowski', ' reva@gmail.com', ' 546-398-7344'),
(11, 'Elizabeth', ' alfreda1@hotmail.com', ' 803-332-6744'),
(12, 'Maria Nave', ' immanuel@gmail.com', ' 743-230-1388'),
(13, 'Elvia Nunez', ' alvena1@gmail.com', ' 307-616-3700'),
(14, 'Lucille Saucedo', ' valentin@gmail.com', ' 223-414-1964'),
(15, 'Billy Jankowski', ' reva@gmail.com', ' 546-398-7344');

Create Database Connection

To create a database connection with the Codeigniter app, take an audacious step towards app/Config/Database.php and carefully insert the database information.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'db_username',
        'password' => 'db_password',
        'database' => 'db_name',
        '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,
    ];

Setting Up Model

Head over to the Models folder, create one user model file and define table name using the $table variable; similarly, use $allowedFields array to add the properties you want to map to the users’ table.

Update app/Models/User.php file.

<?php 

namespace App\Models;
use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'users';
    protected $allowedFields = [
      'name', 
      'email',
      'phone',
    ];
}

Define Logic in Controller

Create UserController file, import User model right before the controller class, create renderDataTable() function and use findAll() method to fetch the records by id and in desc order, including pass the rendered data to view.

Update app/Controllers/UserController.php file.

<?php 

namespace App\Controllers; 

use CodeIgniter\Controller;
use App\Models\User;
 
class UserController extends BaseController {
 
    public function renderDataTable(){
        $model = new User();
        $data['users'] = $model->orderBy('id', 'DESC')->findAll();
        return view('index', $data);
    } 

}

Register or Add Routes

Previously, the formation of the controller decided how to get the data using the model class from the DB; in this section, you will create a route that requests the functions located in the UserController class.

Update app/Config/Routes.php file.

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

$routes->get('/get-users', 'UserController::renderDataTable');

Integrate DataTable in CI View

Create index.php file in the Views folder; within this file, import datatables CSS and scripts; after that, append the table HTML code pass id to the table then call the DataTable() method using the table id.

Update app/Views/index.php file.

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

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Codeigniter 4 DataTables Integration Example</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
	<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
	<style>
		.container {
			max-width: 1000px
		}
	</style>
</head>

<body>

	<div class="container">

		<table class="table" id="dataTable">
			<thead>
				<tr>
					<th>#</th>
					<th>Name</th>
					<th>Email</th>
					<th>Phone</th>
				</tr>
			</thead>
			<tbody>
				<?php if($users): ?>
				<?php foreach($users as $item): ?>
				<tr>
					<td><?php echo $item['id']; ?></td>
					<td><?php echo $item['name']; ?></td>
					<td><?php echo $item['email']; ?></td>
					<td><?php echo $item['phone']; ?></td>
				</tr>
				<?php endforeach; ?>
				<?php endif; ?>
			</tbody>
		</table>

		<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
		<script type="text/javascript" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
		<script>
			$(document).ready(function () {
				$('#dataTable').DataTable();
			});
		</script>
	</div>
</body>

</html>

Invoke App in Browser

In the last segment, we will test the app on the browser, execute the command and use the url to view the app.

php spark serve
http://localhost:8080/get-users

Implement Datatable in Codeigniter

Conclusion

Throughout this intuitive Codeigniter 4 datatables example, we have relentlessly explained the effective and agile instructions to create datatables in the Codeigniter environment in eloquent ways; if you have gone through every step carefully, so by now, you have been able to integrate datatable in the Codeigniter app.