CI 4 provide paginate() function that allow developers to show data in html table with paginated links.
Let’s start to create table and show paginated data from server in codeIgniter 4 with bootstrap:
Step 1: Set up CodeIgniter Project
Download CodeIgniter 4 from the official website:https://codeigniter.com/user_guide/installation/index.html., and extract download zip file in xampp/htdocs directory.
Step 2: Set up Database
Edit .env file from root directory of ci project, and set up database details in it:
database.default.hostname = localhost
database.default.database = your_database_name
database.default.username = your_username
database.default.password = your_password
database.default.DBDriver = MySQLi
Step 3: Create a Controller Class
Create a controller file named PaginationController.php
in App/controllers
directory, and implement methods in it to handle pagination with database:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\UserModel;
class PaginationController extends Controller
{
public function index()
{
$model = new UserModel();
$data = [
'users' => $model->paginate(10),
'pager' => $model->pager
];
return view('users', $data);
}
}
Step 4: Create View
Create a view file named users.php
in app/views
directory to display paginated data with pagination link:
<!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 Tutorial - ItcodStuff.com</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="container">
<div class="row mt-5">
<table class="table table-bordered">
<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 class="row">
<div class="col-md-12">
<div class="row">
<?php if ($pager) :?>
<?php $pagi_path='demo/public/index.php/list'; ?>
<?php $pager->setPath($pagi_path); ?>
<?= $pager->links() ?>
<?php endif ?>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Step 5: Test Application
Type the http://localhost/demo/public/index.php/list url in browser to test the application.