0

我写了一个分页功能,但一直在努力添加“上一个”和“下一个”按钮。任何帮助或指导将不胜感激,我在网上看过,到目前为止还没有提出一个优雅的解决方案。

$result = is database query results.

$per_page = 5;
if($result->num_rows != 0)
{
  $total_results = $result->num_rows;
  $total_pages = ceil($total_results / $per_page);
  if(isset($_GET['page']) && is_numeric($_GET['page']))
  {

    $show_page = $_GET['page'];

    if ($show_page > 0 && $show_page <= $total_pages)
    {
      $start = ($show_page -1) * $per_page;
      $end = $start + $per_page; 
    }
else
{
  $start = 0;
  $end = $per_page; 
}
else
{
 $start = 0;
 $end = $per_page;
}

$pag = '';

for ($i = $start; $i < $end; $i++)
{
// Make sure PHP doesnt show results that do not exist
if ($i == $total_results) { break; }
// Find Specific Row
$result->data_seek($i);
$row = $result->fetch_row();

// label Rows 
$id = $row[0];

    //USE AND DISPLAY RESULTS

    //Pagination
    for ($i = 1; $i <= $total_pages; $i++)
{       
   if($total_pages != 1)
   {
      if(isset($_GET['page']) && $_GET['page'] == $i)
      {
        $pag .= $i ." ";
      }
      else
      {
        $pag .= "<a href='index.php?page=$i'>$i</a>";
      }
   }
    }
}
else
{
 $pag .= 'no results';
}
4

2 回答 2

2

您已经知道您所在的页面:

$_GET['page']

总页数:

$total_pages

所以你可以用它来获得下一个和上一个。

$page = 1;
if(isset($_GET['page']))
    $page = $_GET['page'];

$prev = $page - 1;
if($prev >= 1)
    $pag = "<a href='index.php?page=$prev'>Prev</a>";

for ($i = 1; $i <= $total_pages; $i++)
{       
   if($total_pages != 1)
   {
      if($page == $i)
      {
        $pag .= $i ." ";
      }
      else
      {
        $pag .= "<a href='index.php?page=$i'>$i</a>";
      }
   }
    }
}

$next = $page + 1;
if($next <= $total_pages)
    $pag .= "<a href='index.php?page=$next'>Next</a>";
于 2012-11-29T20:55:36.233 回答
0

有点像这样?

<a href="index.php?page=<?php echo ($_GET['page'] + 1); ?>">Next</a>
于 2012-11-29T20:50:55.037 回答