我有以下分页代码:
$rec_limit = 3;
/* Get total number of records */
$query = "SELECT count(id) FROM news";
$result = mysql_query($query);
if(!$result)
{
die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($result, MYSQL_NUM );
$rec_count = $row[0];
if( isset($_GET{'page'} ) )
{
$page = $_GET{'page'} + 1;
$offset = $rec_limit * $page ;
}
else
{
$page = 0;
$offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);
$query2 = "SELECT * ".
"FROM news ".
"LIMIT $offset, $rec_limit";
$result2 = mysql_query( $query2 );
if(! $result2 )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($result2, MYSQL_ASSOC))
{
echo " ID :{$row['id']} <br> ".
" News : {$row['title']} <br> ".
" Date : {$row['date']} <br> ".
"--------------------------------<br>";
}
if( $page > 0 )
{
$last = $page - 2;
echo "<a href=\"{$_SERVER['PHP_SELF']}?page=$last\">Last 3 Records</a> |";
echo "<a href=\"{$_SERVER['PHP_SELF']}?page=$page\">Next 3 Records</a>";
}
else if( $page == 0 )
{
echo "<a href=\"{$_SERVER['PHP_SELF']}?page=$page\">Next 3 Records</a>";
}
else if( $left_rec < $rec_limit )
{
$last = $page - 2;
echo "<a href=\"{$_SERVER['PHP_SELF']}?page=$last\">Last 3 Records</a>";
}
代码可以根据需要完美地工作,除了a href
部分,即使没有新闻,它也会显示下一个3记录链接。我的意思是,它一直打开空记录的页面! 如何在达到最后一条新闻ID时删除“下一条3条记录”链接。
谢谢
答案 0 :(得分:0)
只需将最后一个条件置于其他两个条件之上并将<
更改为<=
:
if($left_rec <= $rec_limit)
{
$last = $page - 2;
echo "<a href=\"{$_SERVER['PHP_SELF']}?page=$last\">Last 3 Records</a>";
} else if ( $page > 0 )
{
$last = $page - 2;
echo "<a href=\"{$_SERVER['PHP_SELF']}?page=$last\">Last 3 Records</a> |";
echo "<a href=\"{$_SERVER['PHP_SELF']}?page=$page\">Next 3 Records</a>";
}
else if( $page == 0 )
{
echo "<a href=\"{$_SERVER['PHP_SELF']}?page=$page\">Next 3 Records</a>";
}