PHP:在分页中显示z条目中的x到y

时间:2017-08-02 08:33:54

标签: php

我想在搜索结果页面上显示“在x条目中显示yz”的值,但我似乎无法正确计算数学。

以下是我的一些变量:

// Total number of results
$total = mysqli_num_rows($rs);

// Items per page
$item_per_page = 3;

// Page number
$page_number = x;

// break records into pages
$total_pages = ceil($get_total_rows[0] / $item_per_page);

// get starting position to fetch the records
$page_position = (($page_number - 1) * $item_per_page);

这是我试过的:

echo $page_position . ' to ' . ($page_position + $item_per_page) . ' out of ' . $total;

但是,假设我有11条记录,每页显示3条记录。在第4页只有2个结果,但使用上面的代码,它会说"9 to 12 out of 11"

有人可以用一些公式来帮助我计算给定页面上显示的条目数吗?

2 个答案:

答案 0 :(得分:1)

// For none-last page, $page_position should be
$page_position = (($page_number - 1) * $item_per_page) + 1;
// eg: Let's say $page_number = 1, then $page_position should be 1


// And for last page, there's sometimes the count of records not equal to the $item_per_page, so you should directly show the $total.
if ($page_number == $total_pages) {
    echo $page_position . ' to ' . $total . ' out of ' . $total;
}

答案 1 :(得分:-1)

你可以尝试这样的事情

    // Total number of results
    $total = mysqli_num_rows($rs);

    // Items per page
    $item_per_page = 3;

    // Page number
    $page_number = x;

    // break records into pages
    $total_pages = ceil($get_total_rows[0] / $item_per_page);

    // get starting position to fetch the records
    $page_position = (($page_number - 1) * $item_per_page);
    $remaining = $total_pages - ($page_position + $item_per_page);
    if ($remaining < $item_per_page){
      echo $page_position . ' to ' . ($total) . ' out of ' . $total;
    } else {
echo $page_position . ' to ' . ($page_position + $item_per_page) . ' out of ' . $total;
}