Problem in the pagination

Asked

Viewed 55 times

3

I’m making a pagination. So far so good, but when I’m on the home page, it shows the results, everything ok. But when I click to go to the page 2, it only changes the last page result.

example products.php

id 45,46,47,48,49 on this page is all ok. But on the page produtos.php?pagina=1, shows like this 46,47,48,49,50.

    session_start();
    require '../conectaBanco.php';
    $itens_pagina = 5;
    if (isset($_GET['pagina'])) {
    $pagina = $_GET['pagina'];
    } else {
    $pagina = 0;
    }
    $sql_code = "SELECT * FROM produtos LIMIT $pagina, $itens_pagina";
    $execute = $conecta->query($sql_code) or die($$conecta->error);
    $produto = $execute->fetch_assoc();
    $num = $execute->num_rows;
    $num_total = $conecta->query("SELECT * FROM produtos")->num_rows;
    $num_paginas = ceil($num_total / $itens_pagina);

1 answer

1


Try it like this:

session_start();
require '../conectaBanco.php';
$itens_pagina = 5;
if (isset($_GET['pagina']))
    $pagina = $_GET['pagina'] * $itens_pagina ; // mudei aqui
else
    $pagina = 0;

$sql_code = "SELECT * FROM produtos LIMIT $pagina, $itens_pagina";
$execute = $conecta->query($sql_code) or die($$conecta->error);
$produto = $execute->fetch_assoc();
$num = $execute->num_rows;
$num_total = $conecta->query("SELECT * FROM produtos")->num_rows;
$num_paginas = ceil($num_total / $itens_pagina);

When there is a page in the URL, you should multiply that number by the amount of items you want on that page, for example:

  • Page 1 -> $pagina = 1 * 5 = 05, then list from 05, to 10
  • Page 2 -> $pagina = 2 * 5 = 10, then list from 10 to 15
  • Page 3 -> $pagina = 3 * 5 = 15, then list from 15, to 20
  • blz worked :D

  • I added the explanation so you’d understand :)

Browser other questions tagged

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