如何限制分页页面链接?

时间:2014-08-04 03:43:17

标签: php pagination limit paging offset

我有像这样的分页页面链接。和页面一样:

1 2 3 4 5 6 7,8,9,10继续。

但是我想限制这个,所以如果超过5页,它只会显示5个这样的链接:

1 2 3 4 5 ... 97 98 99 其中99是最后一页。

如果你转到下一页,它只会改变这样的第一页:

3 4 5 ... 97 98 99

 function pagination($current_page_number, $total_records_found, $query_string = null)
 {
$page = 1;

echo "Page: ";

for ($total_pages = ($total_records_found/NUMBER_PER_PAGE); $total_pages > 0;   $total_pages--)
{
    if ($page != $current_page_number)
        echo "<a href=\"?page=$page" . (($query_string) ? "&$query_string" : "") .   "\">";

    echo "$page ";


  require_once('inc/database.php'); 

  define("NUMBER_PER_PAGE", 5); //number of records per page of the search results

  $page = ($_GET['page']) ? $_GET['page'] : 1;
  $start = ($page-1) * NUMBER_PER_PAGE;

  $sql = "SELECT * FROM members WHERE 1=1";


    $total_records = mysql_num_rows(mysql_query($sql));

    //we limit our query to the number of results we want per page
    $sql .= " LIMIT $start, " . NUMBER_PER_PAGE;


    // we display our pagination at the top of our search results

    pagination($page, $total_records, "id=$id&username=$username&email=$email");

    $loop = mysql_query($sql)
    or die ('cannot run the query because: ' . mysql_error());

      while ($record = mysql_fetch_assoc($loop))
    echo "<br/>{$record['id']}) " . stripslashes($record['username']) . " -    {$record['email']}";

    echo "<center>" . number_format($total_records) . " search results found</center>";


    if ($page != $current_page_number)
        echo "</a>";

    $page++;

1 个答案:

答案 0 :(得分:0)

分页是已经做过很多次的事情之一,你最好弄清楚如何使用像这样的预制课程http://code.tutsplus.com/tutorials/how-to-paginate-data-with-php--net-2928

您需要做的基础是计算您希望在elipses的两侧看到多少链接...然后创建循环来创建这些链接。 ceil()函数对您来说可能是新的,但它会返回一个总是向上舍入的分数。

$buffer = 3;
$results_per_page = 5;
$page = ($_GET['page']) ? $_GET['page'] : 1;
$start = ($page-1) * $results_per_page;

$sql = "SELECT * FROM members WHERE 1=1";
$total_records = mysql_num_rows(mysql_query($sql));
$total_pages = ceil(intval($total_records) / $results_per_page);

for ($x = $page - $buffer; $x < $page; $x++){
    echo "<a href=\"?page=$x" . (($query_string) ? "&$query_string" : "") .   "\"> $x</a>";
}
echo " ... ";

for ($x = $total_pages - $buffer; $x <= $total_pages; $x++){
    echo "<a href=\"?page=$x" . (($query_string) ? "&$query_string" : "") .   "\"> $x</a>";
}

这个快速的一点代码没有考虑到足够小的结果集以适应一行中的所有链接。这就是为什么我建议使用已存在的分页类。