Limit the number of pages in PHP MYSQL paging

Asked

Viewed 1,060 times

1

I have a pagination in PHP and MYSQLI, and I would like the link of the pages below to be limited, for example:

Pages: 1 2 3 4 5 (goes up to 100), appear only the first 5, if I have on page 10, shows me 8 9 10 11 12, I do not know if you understand me, but what happens to me is that I have a lot of items added in the bank and what happens is that more than 200 pages appear, and I want to show the links of at least 5. Follow 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>";
            }
        ?>

1 answer

2


You need to limit this on 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 the logic: Variables were created to set how many pages to the left, and how many to the right. So the is limited to starting the $i to 2 numbers before the current page, and finish the 2 numbers after the current page. Ex: current page is 5, the for would start at 3 (5-2=3) and end at 7 (5+2=7), result: 3 4 5 6 7

Browser other questions tagged

You are not signed in. Login or sign up in order to post.