Calculating the number of results on a specific page using pagination - PHP

I have a search result from a query MySQLor Arrayor something else. The result gave a variable $totalfiles, for example, 25. The number of results is limited $limit, here 12. The maximum number of calculated pages $maxpageswill be 3.

As we look at the case, we get 12 results for pages 1 and 2 and 1 for page 3.

Can anyone suggest me the easiest way to predict (or estimate) the number of results on a particular page with the help of variables $totalfiles, $limit, $maxpagesand $pagenumberwith the help of PHP ?? I do not think that all these 4 variables are necessary for this.

Thanks in advance.

+3
source share
5 answers

The only page that is allowed to have a number other than $ limit is the last. Do not forget about it. And on the last page there will always be the rest of the integer division

$last_page_items = $totafiles % $limit;

If $ last_page_items is 0, then you have all the pages with $ limit elements

also,

$pages = ceil($totalfiles / $limit);
+7
source

R = number of lines on a given page, P , where P starts with 1.
T = Total lines
L = Lines on page

R = T - ((P-1) * L)

Then just add a check to set R to 0 if R <0.

The code:

function get_num_rows_on_page($page, $total_rows, $per_page) {
    $on_page = $total_rows - ( ($page-1) * $per_page );
    return $on_page < 0 ? 0 : $on_page;
}
+2
source

: Total files, divided by the limit. If the remainder is greater than 0, add one.

$maxpages = $totalfiles/$limit;
if ($totalfiles % $limit > 0) $maxpages++;

: if Page number less than Max page, there are limit results. If Page number is the Max page, there are (Remainder of Total Files divided by limit) results if that remainder is greater than 0, otherwise limit.

$results = $limit;
$rem = $totalfiles % limit;
if ($pagenumber == $maxpages && $rem > 0) $results = $rem;
+1

, , , 3, :

$results_per_page = ($totalfiles/$maxpages);

Otherwise, you already have the number of results per page calculated for your $ limit variable.

0
source

Try the following:

function getPageSize($total, $maxpages, $pagenumber){

    $itemsperpage=intval($total/$maxpages);
    if($pagenumber == $maxpages){
        $itemslastpage=abs($total-($itemsperpage*$maxpages));
        return $itemslastpage;
    }else{
        return $itemsperpage;
    }
}

// should print '5'
echo getPageSize(29,6,6) . "\n";

// should print '7'
echo getPageSize(14,2,1) . "\n";

Please note that this is $limitnot required since it is only used to manage results from the database.

0
source