当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP实现上一篇下一篇的方法实例总结

PHP实现上一篇下一篇的方法实例总结

2017年12月12日  | 移动技术网IT编程  | 我要评论

御宅伴侣桌面精灵,霸世红颜,振业景洲大厦

本文实例分析了php实现上一篇下一篇的方法。分享给大家供大家参考,具体如下:

php实现上一篇下一篇这个主要是通过sql来根据当前的id来进行判断然后筛选出当前id之前的数据或id之后的数据了就这么简单,具体的我们来看看。

实现网站文章里面上一篇和下一篇的sql语句的写法。

当前文章的id为 $article_id,当前文章对应分类的id是$cat_id,那么上一篇就应该是:

复制代码 代码如下:
select max(article_id) from article where article_id < $article_id and cat_id=$cat_id;

执行这段sql语句后得到 $max_id,然后

复制代码 代码如下:
select article_id, title from article where article_id = $max_id;

简化一下,转为子查询即:

复制代码 代码如下:
select article_id, title from article where article_id = (select max(article_id) from article where article_id < $article_id and cat_id=$cat_id);

下一篇为,代码如下:
复制代码 代码如下:
select min(article_id) from article where article_id > $article_id and cat_id=$cat_id;

执行这段sql语句后得到 $min_id,然后:
复制代码 代码如下:
select article_id, title from article where article_id = $min_id;

简化一下,转为子查询即:

复制代码 代码如下:
select article_id, title from article where article_id = (select min(article_id) from article where article_id > $article_id and cat_id=$cat_id);

最后讲一下有很多朋友喜欢使用下面语句

上一篇,代码如下:

select id from table where id10 limit 0,1;

这样肯定没有问题,但是是性能感觉不怎么地.

sql语句优化:

你可以使用union all来实现一条语句取3行数据,但是前提是3个查询的字段要相同,这个查询出来的结果第一行就是上一篇文章,第二行是当前文章,第三行是下一篇文章,代码如下:

复制代码 代码如下:
(select id from table where id < 10 order by id asc limit 1) union all (select id from table where id = 10) union all (select id from table where id > 10 order by id desc limit 1);

现在来看一些cms中的例子phpcms 实现上一篇下一篇.

获取当前浏览文章id:

$id = isset($_get['id']) > 0 ? intval($_get['id']) : "";

下一篇文章:

$query = mysql_query("select id,title from article where id>'$id' order by id asc limit 1");
$next = mysql_fetch_array($query);

上一篇文章:

$query = mysql_query("select id,title from article where id <'$id' order by id desc limit 1");
$prev = mysql_fetch_array($query);

更多关于php相关内容感兴趣的读者可查看本站专题:《php+mysql数据库操作入门教程》、《php+mysqli数据库程序设计技巧总结》、《php面向对象程序设计入门教程》、《php数组(array)操作技巧大全》、《php基本语法入门教程》、《php运算与运算符用法总结》、《php网络编程技巧总结》、《php字符串(string)用法总结》及《php常见数据库操作技巧汇总

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网