PHP简单实现上一页下一页功能示例

yipeiwu_com7年前PHP代码库

本文实例讲述了PHP简单实现上一页下一页功能。分享给大家供大家参考,具体如下:

思路整理:

现在好多人用id的增1和减1实现上一篇和下一篇,但是难道文章ID不会断了吗?所以你要知道上个ID和个ID是多少就OK了。

那怎么解决这个问题呢,很简单!

例子:

假如这篇文章的ID200

<a href="?action=up&id=200">上一篇</a>
<a href="?action=down&id=200">下一篇</a>

如果是实现上一篇就在action=up页面写函数

$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,下一篇)显示出来,当只取一篇的时候,可以省略降序或升序。

具体实现代码:注需要传递参数

前台在上一篇,下一篇处调用:

<?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相关内容感兴趣的读者可查看本站专题:《php常见数据库操作技巧汇总》、《PHP数组(Array)操作技巧大全》、《php排序算法总结》、《PHP常用遍历算法与技巧总结》、《PHP数据结构与算法教程》、《php程序设计算法总结》、《PHP数学运算技巧总结》、《php正则表达式用法总结》、《PHP运算与运算符用法总结》及《php字符串(string)用法总结》

希望本文所述对大家PHP程序设计有所帮助。

相关文章

PHP中4个加速、缓存扩展的区别和选用建议

折腾VPS的朋友,在安装好LNMP等Web运行环境后都会选择一些缓存扩展安装以提高PHP运行速度,常被人介绍的有eAccelerator、memcached、xcache、Alterna...

PHP中strtotime函数使用方法详解

在PHP中有个叫做strtotime的函数。strtotime 实现功能:获取某个日期的时间戳,或获取某个时间的时间戳。strtotime 将任何英文文本的日期时间描述解析为Unix时间...

PHP 高级课程笔记 面向对象

例一: 复制代码 代码如下:<?php // 类的定义 class User { // 属性,注意public、private、protected的作用范围 public $nam...

php 下载保存文件保存到本地的两种实现方法

第一种: <?php function downfile() { $filename=realpath("resume.html"); //文件名 $date=d...

PHP5中的时间相差8小时的解决办法

方法1:        找到php.ini中的“;date.timezone =”这行,将“;”去掉,改成...