I will summarize a technique I use using OFFSET
of 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 show 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 page 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 think this is simple and will suffice, I tried to comment as much as possible.
Note:
The next page link will appear even if it is the last page possible! To solve this I think the best solution is to select all the lines and divide by 15 and check if the user is not on the last page.
I have not used bind_param
because it is only integer and only in LIMIT and OFFSET, but use bind_param
if there are other parameters in WHERE
, for example categories.