Codeigniter 4 Pagination Tutorial: Create Pagination in Codeigniter

Last updated on by Digamber
Pagination is an essential element that creates coherence for better human-computer interaction. Ideally, Pagination is used to unfold the multiple layers of data conjugated on a user’s screen. The Pagination helps in data assortment and gives impetus to scan a large number of data records within seconds. It spontaneously displays the data in an orderly manner rendered from the database.

This tutorial focuses on Codeigniter’s development comprehension. It is a compendium for all the steps that we will take to comprehend the archetype of Codeigniter’s Pagination class.

Codeigniter is a powerful framework it provides robust features for handling Pagination related tasks. You can entirely rely on its built-in pagination class that keeps the impetus of web development steady.

Pagination in Codeigniter 4 Example

In this tutorial, we will understand how to easily create Pagination to display a limited collection of user’s data. We will create the database using PHPMyAdmin and add some random data to it. Thereafter, we will make the PHP query render the User data from the database and display data using Pagination.

Install Codeigniter 4 App

Run command to install Codeigniter 4 application using the composer package manager.

composer create-project codeigniter4/appstarter

After installation, change the name of the application directory such as codeigniter-pagination.

Afterwards, go inside the project folder.

cd codeigniter-pagination

You can also manually download the Codeigniter application.

Show Errors in Codeigniter

Act of recklessness is highly possible specially when you are new to Codeigniter development. Its better to enable the error reporting.

Open app/Config/Boot/development.php and set the display_errors variable’s value to 1 instead of 0. Repeat the same thing in app/Config/Boot/production.php.

ini_set('display_errors', '1');

Configure Database Connection

Include your database name, username and password in application/config/database.php file and make the database connection to handle data dynamically.

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,
	];

Create the users table and insert some random data into it, these records will be used through pagination component in Codeigniter application.

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, 'Paul Bettany', 'paul@gmail.com'),
(2, 'Vanya', 'vanya@gmail.com'),
(3, 'Luther', 'luther@gmail.com'),
(4, 'John Doe', 'john@gmail.com'),
(5, 'Paul Bettany', 'paul@gmail.com'),
(6, 'Vanya', 'vanya@gmail.com'),
(7, 'Luther', 'luther@gmail.com'),
(8, 'Wayne Barrett', 'wayne@gmail.com'),
(9, 'Vincent Ramos', 'ramos@gmail.com'),
(10, 'Susan Warren', 'sussan@gmail.com'),
(11, 'Jason Evans', 'jason@gmail.com'),
(12, 'Madison Simpson', 'madison@gmail.com'),
(13, 'Marvin Ortiz', 'paul@gmail.com'),
(14, 'Felecia Phillips', 'felecia@gmail.com'),
(15, 'Tommy Hernandez', 'hernandez@gmail.com');

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.

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

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

Create Model

Model manifests the particular data and business logic in MVC architecture. It manages the data of the application.

So, we have first create a app/Models/UserModel.php file, thereafter place the following code.

<?php 
namespace App\Models;
use CodeIgniter\Model;

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

We only used handful of values inside the Model, however you can checkout few more model configuration options.

Setting Up Controller

Create app/Controllers/UserController.php and insert the following code inside of it.

Import UserModel at the top section of the User controller, create the new UserModel instance. Make the query fetch the records from the database, load the records in the Codeigniter view.

<?php 
namespace App\Controllers;
use App\Models\UserModel;
use CodeIgniter\Controller;

class UserController extends Controller
{

    public function getAll() {
        $userModel = new UserModel();
 
        $data = [
            'users' => $userModel->paginate(6),
            'pager' => $userModel->pager
        ];
        
        return view('user_view', $data);
    }
 
}

Define Routes

Create the route, It will be used to display the records in tabular form where we can implement pagination. Place the following code in app/Config/Routes.php.

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

Display Pagination

Here the compendium of code describes, we have to display the data using Bootstrap 4 Table with Pagination.

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

<!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 Pagination Example - positronx.io</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>

      <!-- Pagination -->
      <div class="d-flex justify-content-end">
        <?php if ($pager) :?>
        <?php $pagi_path='index.php/users'; ?>
        <?php $pager->setPath($pagi_path); ?>
        <?= $pager->links() ?>
        <?php endif ?>
      </div>

    </div>
  </div>
</body>
</html>

Run Application

Run the following command to start the app:

php spark serve

Check the app on the following URL:

http://localhost:8080/index.php/users

The Bottom Line

Eventually, we have completed this tutorial and learned how to create Pagination in Codeigniter. However, there are many things yet to be done. Still, this tutorial is suitable for beginners who are starting from nowhere.

You can download the full code from GitHub.