Skip to content
Advertisement

Php paging data count show up at each page

I want to show up paging data like Displaying 1 – 5 of 16 . I am trying to do this as below

    $nb_elem_per_page = 3;
    $page = isset($_GET['pg'])?intval($_GET['pg']):0;
    $data = $aawp_table['products'] ;
    $number_of_pages = ceil(count($data)/$nb_elem_per_page);
    $offset = ($page - 1) * $nb_elem_per_page;

Displaying <?php echo  $offset .' - '.$nb_elem_per_page .' of ' . count($data); ?>

But I am not getting proper result for this

Advertisement

Answer

You could have a negative value of $offset if ($page - 1).

You can juste remove it and it will work.

Code :

$nb_data = 20;
$nb_elem_per_page = 3;
$page = isset($_GET['pg']) ? intval($_GET['pg']) : 0;
$number_of_pages = ceil($nb_data / $nb_elem_per_page);
$offset = $page * $nb_elem_per_page;
echo  $offset .' - ' . $nb_elem_per_page .' of ' . $nb_data;
  • If pg is not defined, the result will be 0 - 3 of 20
  • If pg is 0, the result will be 0 - 3 of 20
  • If pg is 1 , the result will be 3 - 3 of 20
  • And so on…

Note that you should test if $page is lower than $number_of_pages to avoid to go to far, or lower than 0.

EDIT A more complete code :

function run_pager($pg = null)
{
    $nb_data = 20;
    $nb_elem_per_page = 3;
    $number_of_pages = ceil($nb_data / $nb_elem_per_page);
    $page = isset($pg) ? intval($pg) : 0;
    if ($page < 0) $page = 0;
    if ($page >= $number_of_pages) $page = $number_of_pages - 1;
    $offset = $page * $nb_elem_per_page;
    $end = $offset + $nb_elem_per_page;
    if ($end > $nb_data) $end = $nb_data;
    return ($offset + 1) .' - ' . ($end) .' of ' . $nb_data;
}
for ($i=0;$i<10;$i++) {
    echo "i=$i : " . run_pager($i) . PHP_EOL;    
}

Output :

i=0 : 1 - 3 of 20
i=1 : 4 - 6 of 20
i=2 : 7 - 9 of 20
i=3 : 10 - 12 of 20
i=4 : 13 - 15 of 20
i=5 : 16 - 18 of 20
i=6 : 19 - 20 of 20
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement