简单的 PHP 分页脚本 [关闭]

Posted

技术标签:

【中文标题】简单的 PHP 分页脚本 [关闭]【英文标题】:Simple PHP Pagination script [closed] 【发布时间】:2011-04-11 22:38:50 【问题描述】:

我有来自数据库的数据行,我想要一个带有简单分页的表,最简单的方法是什么? 如果有人可以提供,我会很高兴。

【问题讨论】:

您使用的是哪个 SQL 数据库(mysql、PostgreSQL、SQL Server)?分页的方式因数据库而异。 【参考方案1】:

这是 html 和代码的混合体,但它非常基础,易于理解,并且我认为应该很容易解耦以满足您的需求。

try 

    // Find out how many items are in the table
    $total = $dbh->query('
        SELECT
            COUNT(*)
        FROM
            table
    ')->fetchColumn();

    // How many items to list per page
    $limit = 20;

    // How many pages will there be
    $pages = ceil($total / $limit);

    // What page are we currently on?
    $page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
        'options' => array(
            'default'   => 1,
            'min_range' => 1,
        ),
    )));

    // Calculate the offset for the query
    $offset = ($page - 1)  * $limit;

    // Some information to display to the user
    $start = $offset + 1;
    $end = min(($offset + $limit), $total);

    // The "back" link
    $prevlink = ($page > 1) ? '<a href="?page=1" title="First page">&laquo;</a> <a href="?page=' . ($page - 1) . '" title="Previous page">&lsaquo;</a>' : '<span class="disabled">&laquo;</span> <span class="disabled">&lsaquo;</span>';

    // The "forward" link
    $nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page">&rsaquo;</a> <a href="?page=' . $pages . '" title="Last page">&raquo;</a>' : '<span class="disabled">&rsaquo;</span> <span class="disabled">&raquo;</span>';

    // Display the paging information
    echo '<div id="paging"><p>', $prevlink, ' Page ', $page, ' of ', $pages, ' pages, displaying ', $start, '-', $end, ' of ', $total, ' results ', $nextlink, ' </p></div>';

    // Prepare the paged query
    $stmt = $dbh->prepare('
        SELECT
            *
        FROM
            table
        ORDER BY
            name
        LIMIT
            :limit
        OFFSET
            :offset
    ');

    // Bind the query params
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();

    // Do we have any results?
    if ($stmt->rowCount() > 0) 
        // Define how we want to fetch the results
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $iterator = new IteratorIterator($stmt);

        // Display the results
        foreach ($iterator as $row) 
            echo '<p>', $row['name'], '</p>';
        

     else 
        echo '<p>No results could be displayed.</p>';
    

 catch (Exception $e) 
    echo '<p>', $e->getMessage(), '</p>';

【讨论】:

这段代码不错。可能值得检查 $total == 0 是否在 COUNT(*) 之后以避免所有不必要的逻辑(即仅向用户显示“未找到结果”而不是构建用于分页的 HTML 等。 问题可能出在“$total”上。如果使用“GROUP BY”sql 部分从数据库读取数据,则总记录变得无关紧要。我使用包装器“SELECT count(*) AS count FROM (SELECT...) AS output”来获取总数。【参考方案2】:

我发现的一些容易理解的教程是:

http://www.phpfreaks.com/tutorial/basic-pagination

将您的列表分成页面大小的块并一次只查询一个块更有意义。这大大减少了服务器处理时间和页面加载时间,并为您的用户提供了更小的信息来消化,因此他不会因您试图喂给他的任何废话而窒息。这样做的行为称为分页。

一个基本的分页程序起初看起来很长而且很吓人,但一旦你 闭上眼睛,深呼吸,看着每一片 单独编写脚本,您会发现它实际上非常简单

脚本:

// find out how many rows are in the table 
$sql = "SELECT COUNT(*) FROM numbers";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) 
   // cast var as int
   $currentpage = (int) $_GET['currentpage'];
 else 
   // default page num
   $currentpage = 1;
 // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) 
   // set current page to last page
   $currentpage = $totalpages;
 // end if
// if current page is less than first page...
if ($currentpage < 1) 
   // set current page to first page
   $currentpage = 1;
 // end if

// the offset of the list, based on current page 
$offset = ($currentpage - 1) * $rowsperpage;

// get the info from the db 
$sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);

// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) 
   // echo data
   echo $list['id'] . " : " . $list['number'] . "<br />";
 // end while

/******  build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) 
   // show << link to go back to page 1
   echo " <a href='$_SERVER['PHP_SELF']?currentpage=1'><<</a> ";
   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page
   echo " <a href='$_SERVER['PHP_SELF']?currentpage=$prevpage'><</a> ";
 // end if 

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) 
   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) 
      // if we're on current page...
      if ($x == $currentpage) 
         // 'highlight' it but don't make a link
         echo " [<b>$x</b>] ";
      // if not current page...
       else 
         // make it a link
         echo " <a href='$_SERVER['PHP_SELF']?currentpage=$x'>$x</a> ";
       // end else
    // end if 
 // end for

// if not on last page, show forward and last page links        
if ($currentpage != $totalpages) 
   // get next page
   $nextpage = $currentpage + 1;
    // echo forward link for next page 
   echo " <a href='$_SERVER['PHP_SELF']?currentpage=$nextpage'>></a> ";
   // echo forward link for lastpage
   echo " <a href='$_SERVER['PHP_SELF']?currentpage=$totalpages'>>></a> ";
 // end if
/****** end build pagination links ******/
?>
http://www.tonymarston.net/php-mysql/pagination.html

本教程适用于希望让用户能够以可管理的块而不是一次性完成大量数据库行的能力来逐步完成大量数据库行的开发人员。

【讨论】:

这正是我正在寻找的分页类型。谢谢你编造:)【参考方案3】:
 <?php
// Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)

mysql_connect("DATABASE_Host_Here","DATABASE_Username_Here","DATABASE_Password_Here") or die (mysql_error());
mysql_select_db("DATABASE_Name_Here") or die (mysql_error());
//////////////  QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn']))  // Get pn from URL vars if it is present
    $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
    //$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
 else  // If the pn URL variable is not present force it to be value of page number 1
    $pn = 1;

//This is where we set how many database items to show on each page
$itemsPerPage = 10;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1)  // If it is less than 1
    $pn = 1; // force if to be 1
 else if ($pn > $lastPage)  // if it is greater than $lastpage
    $pn = $lastPage; // force it to be $lastpage's value

// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) 
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
 else if ($pn == $lastPage) 
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
 else if ($pn > 2 && $pn < ($lastPage - 1)) 
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> &nbsp;';
 else if ($pn > 1 && $pn < $lastPage) 
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';

// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
//////////////////////////////// END Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1")
    // This shows the user what page they are on, and the total number of pages
    $paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. '&nbsp;  &nbsp;  &nbsp; ';
    // If we are not on page 1 we can place the Back button
    if ($pn != 1) 
        $previous = $pn - 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
    
    // Lay in the clickable numbers display here between the Back and Next links
    $paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
    // If we are not on the very last page we can place the Next button
    if ($pn != $lastPage) 
        $nextPage = $pn + 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
    

///////////////////////////////////// END Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2))

    $id = $row["id"];
    $firstname = $row["firstname"];
    $country = $row["country"];

    $outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';

 // close while loop
?>
<html>
<head>
<title>Simple Pagination</title>
</head>
<body>
   <div style="margin-left:64px; margin-right:64px;">
     <h2>Total Items: <?php echo $nr; ?></h2>
   </div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
      <div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
</body>
</html> 

【讨论】:

以上是关于简单的 PHP 分页脚本 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

如何禁用和隐藏反应表的分页页脚?

在 php 中添加页眉/页脚(初级查询)[关闭]

如何在 PHP 中实现分页? [关闭]

php 向页脚添加JS,HTML或任何脚本

创建 PHP 页眉/页脚

使用 Jquery、PHP、Mysql 进行 Ajax 分页 [关闭]