I found pagination library for Codeigniter 4 on github with this link https://github.com/KejawenLab/CI4Pager . I followed every step, But I get issue on displaying data, I get all the data even I provide a number of limit to be shown per page. But for pagination links it work correct. Please help, how can I limit number of result.
Here is my Code
//controller
public function index()
{
helper('paginator');
$db = \Config\Database::connect();
$result = $db->query('SELECT * FROM users');
$paginator = \App\Libraries\Paginator::createFromResult($result, 1, 1);
return view('page', ['paginator'=> $paginator]);
}
//view
<?php foreach($paginator->getResults() as $row):?>
<div><?= $row['username'] ?></div>
<?php endforeach;?>
<?= ci_pager($paginator, [
'base_url' => '/vyombo',
'current_text' => 'Current Page',
'total_text' => 'Total Records',
]);
?>
There's no need for an external library. Codeigniter 4 supports pagination out of the box.
You can either paginate query results or manually paginate the array.
https://codeigniter.com/user_guide/libraries/pagination.html?highlight=pagination
In case you're doing the queries right in the controller, and that is far from ideal. In your case you want to create a model to handle that and then use that model.
// In the Controller
public function index()
{
$userModel = new \App\Models\UserModel();
$pageModel = new \App\Models\PageModel();
$data = [
'users' => $userModel->paginate(10, 'group1'),
'pages' => $pageModel->paginate(15, 'group2'),
'pager' => $userModel->pager
];
echo view('users/index', $data);
}
Then in your view you can either get the full links or simple links.
// In the views:
<?= $pager->links('group1') ?>
<?= $pager->simpleLinks('group2') ?>
In case you still want to manually paginate your query you can do something like this:
Lets say you have a query string called page=1. Then you want 10 elements per page.
Just do your query like:
$limit = 10;
$offset = 10 * ($_GET['page'] - 1);
SELECT *
FROM articles
LIMIT $limit, $offset;
Then to print the pagination links in your view you would just use:
<?= $pager->makeLinks($_GET['page'], $limit, $total) ?>
So for your pagination you always need two queries. One that will give you the current page and another one to give you the total results.