本文实例讲述了PHP简单实现上一页下一页功能。分享给大家供大家参考,具体如下:
思路整理:
现在好多人用id的增1和减1实现上一篇和下一篇,但是难道文章ID不会断了吗?所以你要知道上个ID和个ID是多少就OK了。
那怎么解决这个问题呢,很简单!
例子:
假如这篇文章的ID200
1
2
|
< a href = "?action=up&id=200" >上一篇</ a >
< a href = "?action=down&id=200" >下一篇</ a >
|
如果是实现上一篇就在action=up页面写函数
1
2
3
4
5
6
7
8
9
|
$id = $_GET [ 'id' ];
//上一篇:
$sql = select * from article where id < '.$id.' order by id desc limit 0,1';
$rs = mysql_query( $sql );
$row = mysql_fetch_array ( $rs );
//下一篇:
$sql = select * from article where id < '.$id.' order by id asc limit 0,1';
$rs = mysql_query( $sql );
$row = mysql_fetch_array ( $rs );
|
原理,查询比当前ID小(where id < '.$id.'上一篇)和比当前ID大(where id > '.$id.'下一篇)的1条(limit 0,1)数据,并按降序(desc,上一篇)和升序(asc,下一篇)显示出来,当只取一篇的时候,可以省略降序或升序。
具体实现代码:注需要传递参数
前台在上一篇,下一篇处调用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<?php
echo GetPreNext(pre,news, $_REQUEST [catid], $_REQUEST [id]);?>
//显示上一篇下一篇
function GetPreNext( $gtype , $table , $catid , $id ){
$preR =mysql_fetch_array(mysql_query( "select * from " . $table . " where catid=" . $catid . " and id<$id order by id desc limit 0,1" )); //id比传入id小的最近一条
$nextR =mysql_fetch_array(mysql_query( "select * from " . $table . " where catid=" . $catid . " and id>$id order by id asc limit 0,1" )); //id比传入id大的最近一条
$next = ( is_array ( $nextR ) ? " where id={$nextR['id']} " : ' where 1>2 ' );
$pre = ( is_array ( $preR ) ? " where id={$preR['id']} " : ' where 1>2 ' );
$query = "Select * from " . $table . " " ;
$nextRow =mysql_query( $query . $next );
$preRow = mysql_query( $query . $pre );
if ( $PreNext =mysql_fetch_array( $preRow ))
{
echo $PreNext [ 'pre' ] = "上一篇:<a href='newsshow.php?id=" . $preR ['id ']."&&catid=".$catid."' >". $PreNext [ 'title' ]. "</a> " ;
}
else
{
echo $PreNext [ 'pre' ] = "上一篇:没有了 " ;
}
if ( $PreNext =mysql_fetch_array( $nextRow ))
{
echo $PreNext [ 'next' ] = "下一篇:<a href='newsshow.php?id=" . $nextR ['id ']."&&catid=".$catid."' >". $PreNext [ 'title' ]. "</a> " ;
}
else
{
echo $PreNext [ 'next' ] = "下一篇:没有了 " ;
}
}
|
代码经测试可用
希望本文所述对大家PHP程序设计有所帮助。