I have a pagination in PHP, which is like in the following image:
However, the number of pages increases as I enter more records into the database, since it displays 10 records per page. I would like that, for example, in my pagination it would show from 1 to 10, and that when it reaches 10, it would show from 10 to 20... I don't know if I'm explaining myself.
I leave the PHP code that I use.
<nav aria-label="Page navigation" class="text-center">
<ul class="pagination">
<?php
if ($total_paginas > 1) {
if ($pagina != 1)
echo '<li><a href="'.$url.'?pagina='.($pagina-1).'" aria-label="Previous"><span aria-hidden="true">«</span></a></li>';
for ($i = 1; $i <=$total_paginas; $i++){
if ($pagina == $i)
echo '<li class="active"><a href="#">'.$pagina.'</a></li>';
else
echo '<li><a href="'.$url.'?pagina='.$i.'">'.$i.'</a></li>';
}
if ($pagina != $total_paginas) {
echo '<li><a href="'.$url.'?pagina='.($pagina+1).'"><span aria-hidden="true">»</span></a></li>';
}
}
?>
</ul>
</nav>
Here I leave you an option based on your code and with minimal changes on it.
The idea is quite simple (although I don't know if I will explain it well) and it consists of the following: always show a maximum of 10 links that will start with the unit and end with said unit+9 (or the total pages if unit+9 is elderly). That means that for page 5, the links displayed will be from 1 to 10; for page 13, the links will be from 11 to 20, etc.
To do this, it is necessary to: calculate what will be the first number and the last number to be displayed, and make the loop be only between them. Then, when showing the arrows, it will be necessary to check if the first page is less than 10 (in which case the arrow to the left will not be shown) or if the last page is equal to the total number of pages (in which case it will not be shown). the arrow to the right).
Here is an example of how it would be done:
Doing something similar to what Alvaro did, taking your code as a base, this is a slightly different version, the goals are:
The idea of this answer is to add an option for those who encounter this question "in the future".
The same is to change a little the concept of what you use now. I do it in such a way that the pagination is done in a class and then in the
PHP
, I call the pagination.I have this file for a connection
PDO
, but if you search the Internet, you will surely find it formysql
ormysqli
The call in the code would be: