本文實例講述了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程序設計有所幫助。