Limit amount of pages in PHP MYSQL pagination

0

I have a page in PHP and MYSQLI, and I would like the links on the pages below to be limited, for example:

Pages: 1 2 3 4 5 (up to 100), only the first 5 appear, if I have on page 10, show me 8 9 10 11 12, I do not know if they understood me, but what happens to me is that I have a lot of items added in the bank and what happens is that it appears more than 200 pages, and I want it to show the links of at least 5. Here is the code:

<?php
            $pagina = (isset($_GET['pagina']))? $_GET['pagina'] : 1; 

            $banco = mysqli_query($conecta, "SELECT * FROM produtos WHERE empresa='1' AND ativo='1'"); 

            $total = mysqli_num_rows($banco); 

            $registros = 10;

            $numPaginas = ceil($total/$registros);

            $inicio = ($registros*$pagina)-$registros; 

            $banco = mysqli_query($conecta, "SELECT * FROM produtos WHERE empresa='1' AND ativo='1' LIMIT $inicio,$registros"); 
            $total = mysqli_num_rows($banco); 

            while($exibe_pecas = mysqli_fetch_array($banco)) { 
        ?>
        <div class="conteudo_p">
            <div class="codigo_p"><?php echo $exibe_pecas['codigo']; ?></div>
            <div class="nome_p"><?php echo $exibe_pecas['nome']; ?></div>
            <div class="quantidade_p"><?php echo $exibe_pecas['qtde_estoque']; ?></div>
            <div class="preco_p">R$ <?php echo $exibe_pecas['prc_venda']; ?></div>
            <div class="acao_p">#</div>
        </div>
        <?php } ?>
        <?php
            if($pagina > 1) {
                echo "<a href='index.php?pagina=".($pagina - 1)."' class='controle'>&laquo; anterior</a>";
            }

            for($i = 1; $i < $numPaginas; $i++) {
                $ativo = ($i == $pagina) ? 'numativo' : '';
                echo "<a href='index.php?pagina=".$i."' class='numero ".$ativo."'> ".$i." </a>";
            }

            if($pagina < $numPaginas) {
                echo "<a href='index.php?pagina=".($pagina + 1)."' class='controle'>proximo &raquo;</a>";
            }
        ?>
    
asked by anonymous 29.03.2018 / 21:35

1 answer

1

You need to limit this in for :

$margemDireita = 2;
$margemEsquerda = ($pagina > 2) ? 2 : 0;

for ($i = $pagina - $margemEsquerda; $i < $pagina + $margemDireita; $i++) {
   $ativo = ($i == $pagina) ? 'numativo' : '';
   echo "<a href='index.php?pagina=".$i."' class='numero ".$ativo."'> ".$i." </a>";
}

Understanding logic: Variables have been created to set how many pages to the left, and how many to the right. So for is just getting the $ i 2 numbers before the current page, and finalize the 2 numbers after the current page. Ex: current page is 5, the for would start in 3 (5-2 = 3) and would end in 7 (5 + 2 = 7), result: 3 4 5 6 7

    
29.03.2018 / 22:08