How to make PHP and Mysql paging?

Asked

Viewed 23,785 times

7

I want to make a pagination on my blog. I’m not going to have 50 posts on the first page, so I want to limit the page to the last 15 posts added and then by clicking on the "Older posts" button will show me the older posts. In the background I don’t want to load the page full of posts, basically it’s like Google history, we have our history and it doesn’t appear everything on the page since we installed it, we have buttons saying "older", "newer".

  • Welcome to Stack Overflow in Portuguese! Do the post’s come from BD? Before showing you know how many posts are?

  • yes the post’s come from the comic

  • Show the code you have to be easier to answer the question.

  • the code to show you the posts are not yet made I wanted a basis

  • Hello, welcome to [en.so]. What you are asking involves various problems, could you [dit] the question indicating in which part you are struggling? Would it be about how to take the posts from the bank by blocks? Or about how to display this on the page?

  • 1

    @Cloud I don’t think anyone quite understood your question as already commented above. Are you blogging from scratch? So probably your question is actually how to query a database and should describe what technologies are being used. Or would it be a Wordpress template? In this case there are specific wordpress commands to make the pagination for you. Anyway, you need to further detail what you want, otherwise no one will simply create an example blog just to answer this question.

  • sorry for my explanation, yes I started a blog from scratch but I already have all the Divs all http://gyazo.com/817d5deec09f32476250502fe61cc6f2 I am already adding from the administrative panel with link to the database, what will happen is that the site user will post’s and more post’s and blog page will get very big, full of posts like this http://gyazo.com/44a9a885fc5761e7a6173b1b943f2802

  • what I want is to limit the post imagine when the blog page has 100 posts so it will show the 20 last posts added recently and then I will have the "Older posts" button that will then show me the rest of the older posts

  • http://gyazo.com/5a7fa312a7114e8f2fd9f210d3c77429 this is what I want a button to show old posts by clicking on it will update me and show me old posts

  • This limit is also known as paging, when making the query it is necessary to use a limit/off set and a order by <campo> desc for example by id or creation date this will bring the last entered records

  • As you’ve already said, your problem is in doing paging. Rephrase your question to make it about that subject, for example: "How do PHP and Mysql pagination?". Then there will probably be answers for you.

  • 1

    cloud, put these details of your comments in the question.

  • I believe that is exactly what @Lost commented, what you seek is the command LIMIT mysql.

  • As @bfavaretto said, would it just be a set of results from a single category ? Or would it be multiple results from different categories ? Explain it better, if possible.

Show 9 more comments

3 answers

12

Following is an example of a code for pagination, all lines are commented.

<?php
    //inclusão da conexão com banco de dados
    require('config/conectaBd.php');
    //A quantidade de valor a ser exibida
    $quantidade = 3;
    //a pagina atual
    $pagina     = (isset($_GET['pagina'])) ? (int)$_GET['pagina'] : 1;
    //Calcula a pagina de qual valor será exibido
    $inicio     = ($quantidade * $pagina) - $quantidade;

    //Monta o SQL com LIMIT para exibição dos dados  
    $sql = "SELECT * FROM novidades ORDER BY  data DESC LIMIT $inicio, $quantidade";
    //Executa o SQL
    $qr  = mysql_query($sql) or die(mysql_error());
    //Percorre os campos da tabela
    while($ln = mysql_fetch_assoc($qr)){?>

                <div id="noticias">
                <div style="border-bottom:1px dotted #CCC; width:700px; padding:15px; margin-left:-65px;">
            <!--echo '<div style="color:#999; font-size:10px; width:auto; margin-top:2px; margin-bottom:-3px;">'.formata_data($data).'</div>';-->

                <div id="titulo">
        <?php echo $ln['titulo'];?>
                </div>
        <img src="fotos/<?php echo $ln['foto'];?> " style="width:250px; float:left; margin-right:25px; margin-bottom:15px; padding:10px; border:2px solid #D8D8D8;"/>
        <div id="descricao">
        <?php echo $ln['descricao']?></div>
                </div>
                </div>
                </div>
        <?php }?>


        <?php
  /**
   * SEGUNDA PARTE DA PAGINAÇÃO
   */
  //SQL para saber o total
  $sqlTotal   = "SELECT id FROM novidades";
  //Executa o SQL
  $qrTotal    = mysql_query($sqlTotal) or die(mysql_error());
  //Total de Registro na tabela
  $numTotal   = mysql_num_rows($qrTotal);
  //O calculo do Total de página ser exibido
  $totalPagina= ceil($numTotal/$quantidade);
   /**
    * Defini o valor máximo a ser exibida na página tanto para direita quando para esquerda
    */
   $exibir = 3;
   /**
    * Aqui montará o link que voltará uma pagina
    * Caso o valor seja zero, por padrão ficará o valor 1
    */
   $anterior  = (($pagina - 1) == 0) ? 1 : $pagina - 1;
   /**
    * Aqui montará o link que ir para proxima pagina
    * Caso pagina +1 for maior ou igual ao total, ele terá o valor do total
    * caso contrario, ele pegar o valor da página + 1
    */
   $posterior = (($pagina+1) >= $totalPagina) ? $totalPagina : $pagina+1;
   /**
    * Agora monta o Link paar Primeira Página
    * Depois O link para voltar uma página
    */
  /**
    * Agora monta o Link para Próxima Página
    * Depois O link para Última Página
    */
    ?>
    <div id="navegacao">
        <?php
        echo '<a href="?pagina=1">primeira</a> | ';
        echo "<a href=\"?pagina=$anterior\">anterior</a> | ";
    ?>
        <?php
         /**
    * O loop para exibir os valores à esquerda
    */
   for($i = $pagina-$exibir; $i <= $pagina-1; $i++){
       if($i > 0)
        echo '<a href="?pagina='.$i.'"> '.$i.' </a>';
  }

  echo '<a href="?pagina='.$pagina.'"><strong>'.$pagina.'</strong></a>';

  for($i = $pagina+1; $i < $pagina+$exibir; $i++){
       if($i <= $totalPagina)
        echo '<a href="?pagina='.$i.'"> '.$i.' </a>';
  }

   /**
    * Depois o link da página atual
    */
   /**
    * O loop para exibir os valores à direita
    */

    ?>
    <?php echo " | <a href=\"?pagina=$posterior\">próxima</a> | ";
    echo "  <a href=\"?pagina=$totalPagina\">última</a>";
    ?>
  • 5

    You can even use the example of Douglas Bernadino, but use PDO or mysqli. mysql extensions are deprecated and mysqli in a short future too!

3

I’ll summarize a technique I use using the OFFSET mysql.

<?php

$limite = 15; // Limite por página

// Pega página atual, se houver e for válido (maior que zero!)
if( isset( $_GET['pagina'] ) && (int)$_GET['pagina'] >= 0){
    $pagina = (int)$_GET['pagina'];
}else{
    $pagina = 0;
}

// Calcula o offset
$offset = $limite * $pagina;

// Se for 0 será 15*0 que será 0, começando do inicio
// Se for 1 será 15*1 que irá começar do 15 ignorando os 15 anteriores. ;)

$postagem = $mysqli->query('SELECT * FROM `post` ORDER BY id DESC LIMIT '.$limite.' OFFSET '.$offset);
?>

After this just display as you want, for example:

<?php

while($info = $postagem->fetch_array()){
// Loop finito para repetir para cada linha existente
?>

<!-- HTML PARA EXIBIÇÃO -->
<h1><?= $info['titulo'] ?></h1> 
<div class="data"><?= $info['dataHumano'] ?></div>
<div class="descricao"><?= $info['desc'] ?></div>
<!-- HTML PARA EXIBIÇÃO -->

<?php
}
?>

To paginate use something similar to:

This will trigger the $_GET['pagina'] mentioned in the first part.

<?php
if($pagina !== 0){ // Sem isto irá exibir "Página Anterior" na primeira página.
?>
<a href="meulink.com?pagina=<?php echo $pagina-1; ?>">Página Anterior</a>
<?php
}
?>
<a href="meulink.com?pagina=<?php echo $pagina+1; ?>">Página Posterior</a>

I believe this is simple and will suffice, I have tried to comment as much as possible.

Note:

The link to next page will be displayed even if it is the last possible page! To solve this I think the best solution is to select all lines and divide by 15 and check that the user is not on the last page.

I didn’t use the bind_param because they are only whole numbers and only in LIMIT and OFFSET, but use the bind_param if there are other parameters in the WHERE, for example categories.

0

My site has 180 products , can use my code works perfectly:

<?php
echo'<table width="88%" height="10" cellspacing="0" cellpadding="0"><tr>';
$conn = new PDO("mysql:host=localhost;dbname=loja", "root", "");
$stmt = $conn->prepare("SELECT * FROM `produtos` ORDER BY `id` ASC ");
$stmt->execute( );
$linha = $stmt->fetch(PDO::FETCH_ASSOC);
while($linha = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo'<br>';
    echo'<p><td align=center ><h2><font size="5" face="Trebuchet MS">'.$linha['nome'].'</font></font></p></h2>';
    echo "<div align=center ><img src='".$linha['foto']."' width='160' height='160' border='0'></p>";
    echo '<a href="carrinho.php?acao=add&id='.$linha['id'].'"><button type="button" name="" value="" class="quero">Eu Quero!</button>';
}
echo "</tr></table>";
?>

Browser other questions tagged

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