I'm working with PHP, I have a paginated list that works fine, but when loading many records I realized a detail. The pagination should only show 5 pages, but my pagination shows me all the pages, creating one big row with page numbers. I share my code, hoping that someone can guide me to solve this problem.
SO IT SHOULD BE
THIS IS HOW IT CURRENTLY WORKS
$sql_register = $db->query("SELECT COUNT(*) as total_registro FROM pasantia");
$result_register = mysqli_fetch_array($sql_register);
$total_registro = $result_register['total_registro'];
$solicitudesPorPagina = 10;
$pagina = 1;
if (isset($_GET["pagina"]))
{
$pagina = $_GET["pagina"];
}
$limit = $solicitudesPorPagina;
$offset = ($pagina - 1) * $solicitudesPorPagina;
$paginas = ceil($total_registro / $solicitudesPorPagina);
/////////////////////////////PAGINATION//////////////////// //////
<nav aria-label="Page navigation example">
<div class="row">
<div class="col-xs-12 col-sm-6">
<p>Mostrando <?php echo $solicitudesPorPagina ?> de <?php echo $total_registro ?>
solicitudes disponibles</p>
</div>
<div class="col-xs-12 col-sm-6">
<p>Página <?php echo $pagina ?> de <?php echo $paginas ?> </p>
</div>
</div>
<ul class="pagination justify-content-right">
<?php if ($pagina > 1) { ?>
<li>
<a href="./pasantia.php?pagina=<?php echo $pagina - 1 ?>">
<span aria-hidden="true">«</span>
</a>
</li>
<?php } ?>
<?php for ($x = 1; $x <= $paginas; $x++) { ?>
<li class="<?php if ($x == $pagina) echo "active" ?>">
<a href="./pasantia.php?pagina=<?php echo $x ?>">
<?php echo $x ?></a>
</li>
<?php } ?>
<?php if ($pagina < $paginas) { ?>
<li>
<a href="./pasantia.php?pagina=<?php echo $pagina + 1 ?>">
<span aria-hidden="true">»</span>
</a>
</li>
<?php } ?>
</ul>
There are more ways to solve it, but this could be one of them. I focus on the loop
for ($x = 1; $x <= $paginas; $x++)
that you could change to the following block of code.At the beginning I define a variable
$margen_pags = 2
because I understand that you would want, for example if you are in 6, see 4-5-6-7-8, but you can change it to any value if for example tomorrow you want 3 before and three after.And an important issue is that I put the code understanding that the first page starts counting at 1. If it started at 0, some retouching would have to be done.
It might also be worth assessing what happens if there are no results (
$total_registro == 0
), because in that case there would be no paginator and this code can cause an error, so I don't know if you evaluate it before anything else (I don't see where), but It is important.I hope it's worth it