0
votes

This code to generate a paginator isn't working as expected, what could be the problem?

This function obtains the HTML links for a paginator given some data about the results the current page is showing. $ruta is the base URL, $pagina is the current page for which I want to generate pagination links, $limite is the number of result that each page shows, $total is the total of results to be paged.

function generarPaginador($ruta, $pagina, $limite, $total)
{
    // Traducciones
    $textoPrimera = _('Primera');
    $textoUltima = _('Última');

    // Variables para la numeración de los enlaces para paginación
    $primera = 1;
    $ultima = ceil($total / $limite); //I was using floor but thanks to the answer I could verify that ceil gives me the correct pagination links for the given parameters
    $anterior = $pagina == 1 ? 1 : $pagina - 1;
    $siguiente = ( ( $pagina + 1) > $ultima) ? $ultima : $pagina + 1;

    if ($ultima == 1) {
        return '';
    }

    // ENLACES: Primeros
    $enlaces = '';
    $enlaces .= "<span><a href=\"$ruta?pag=$primera&max=$limite\">$textoPrimera</a></span>";
    $enlaces .= "<span><a href=\"$ruta?pag=$anterior&max=$limite\">&lt;</a></span>";

    // ENLACES: Previos a la página actual
    $i = ( $pagina - 3) > 0 ? $pagina - 3 : 1;
    while ($i < $pagina) {
        $enlaces .= "<span><a href=\"$ruta?pag=$i&max=$limite\">$i</a></span>";
        $i++;
    }

    // ENLACES: Página actual
    $enlaces .= "<span class=\"current\">$pagina</span>";

    // ENLACES: Siguientes a la página actual
    $i = $pagina + 1;
    $tamano = $pagina + 3;
    while (($i <= $ultima ) && ($i <= $tamano)) {
        $enlaces .= "<span><a href=\"$ruta?pag=$i&max=$limite\">$i</a></span>";
        $i++;
    }

    // ENLACES: Últimos enlaces
    $enlaces .= "<span><a href=\"$ruta?pag=$siguiente&max=$limite\">&gt;</a></span>";
    $enlaces .= "<span><a href=\"$ruta?pag=$ultima&max=$limite\">$textoUltima</a></span>";

    return $enlaces;
}

For example I want to generate the links of the paginator for the page 2, there are 37 total results, but the web page just shows 10 results per page. The base url is /busqueda/resultados/

If I pass those parameters to the function it generates 3 links without problem for the 3 first pages with the first 30 results, but it should also generate a 4th link for the last page (because each page contains 10 max, the first three contains 10 each one, 30 in total, but the 4th contains the remaining 7 and there should be a link to it).

1
Why would you be passing the number of results into the function?Mike Brant
I do a count of some rows in a database table, then after that, I pass the result of the count to this function so it can generate the links of the paginator for the given SQL query. So I need to pass the results.Saruva

1 Answers

1
votes

This should be as simple as changing floor to ceil.