用PHP显示页面编号

时间:2014-11-09 16:30:22

标签: php mysql

我在PHP中使用这个coed来显示mysql数据库中记录的下一个和上一个按钮:

$sql="SELECT * from customer";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$MaxRowsPerPage = 25;
$total_records = mysql_num_rows($rs);
$total_pages = ceil($total_records / $MaxRowsPerPage);
if(isset($_GET["page"])) {
    $page  = $_GET["page"];
} else {
    $page=1;
}
$start_from = ($page-1) * $MaxRowsPerPage;
$sql.=" LIMIT $start_from, $MaxRowsPerPage";

我正在回显$total_records以显示总金额,如何显示当前页面上的数字。例如,在第1页上,它将显示记录 1到25 (因为每页的最大行数为25),然后第2页将显示记录 26到50 等等上...

1 个答案:

答案 0 :(得分:2)

有很多方法可以做到这一点,但这是我做的一个简单的分页示例。它还将显示1-25,26-50等。它的评论很多,所以应该很容易理解。

<?php
// Connect to database
include 'includes/db_connect.php';

// Find total number of rows in table
$result = mysql_query("SELECT COUNT(*) FROM example_table");
$row = mysql_fetch_array($result);
$total_rows = $row[0];

// Set rows per page
$rows_per_page = 25;

// Calculate total number of pages
$total_pages = ceil($total_rows / $rows_per_page);

// Get current page
$current_page = (isset($_GET['p']) && $_GET['p'] > 0) ? (int) $_GET['p'] : 1;

// If current page is greater than last page, set it to last.
if ($current_page > $total_pages)
    $current_page = $total_pages;

// Set starting post
$offset = ($current_page - 1) * $rows_per_page;

// Get rows from database
$result = mysql_query("SELECT * FROM example_table LIMIT $offset, $rows_per_page");

// Print rows
echo '<hr>';
while($row = mysql_fetch_array($result))
{
    echo $row['id'].'<br />';
    echo $row['text'];
    echo '<hr>';
}

// Build navigation
// Range of pages on each side of current page in navigation
$range = 4;

// Create navigation link for previous and first page.
if ($current_page > 1)
{
    $back = $current_page - 1;
    echo ' <a href="?p='.$back.'"> PREV</a> ';
    if ($current_page > ($range + 1))
        echo ' <a href="?p=1">1</a>... ';
}
else
    echo ' PREV ';

// Create page links, based on chosen range.
for ($i = $current_page - $range; $i < ($current_page + $range) + 1; $i++)
{
   if ($i > 0 && $i <= $total_pages)
      if ($i == $current_page)
         echo ' [<strong>'.$i.'</strong>] ';
      else
         echo ' <a href="?p='.$i.'">'.$i.'</a> ';
}

 // Create navigation link for next and last page.
if ($current_page != $total_pages)
{
    $next = $current_page + 1;
    if (($current_page + $range) < $total_pages)
        echo ' ...<a href="?p='.$total_pages.'">'.$total_pages.'</a> ';

    echo ' <a href="?p='.$next.'">NEXT </a> ';
}
else
    echo ' NEXT ';
?>