本文實例講述了PHP簡單實現(xiàn)上一頁下一頁功能。分享給大家供大家參考,具體如下:
思路整理:
現(xiàn)在好多人用id的增1和減1實現(xiàn)上一篇和下一篇,但是難道文章ID不會斷了嗎?所以你要知道上個ID和個ID是多少就OK了。
那怎么解決這個問題呢,很簡單!
例子:
假如這篇文章的ID200
<a href="?action=up&id=200">上一篇</a><a href="?action=down&id=200">下一篇</a>
如果是實現(xiàn)上一篇就在action=up頁面寫函數(shù)
$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);
原理,查詢比當(dāng)前ID小(where id < '.$id.'上一篇)和比當(dāng)前ID大(where id > '.$id.'下一篇)的1條(limit 0,1)數(shù)據(jù),并按降序(desc,上一篇)和升序(asc,下一篇)顯示出來,當(dāng)只取一篇的時候,可以省略降序或升序。
具體實現(xiàn)代碼:注需要傳遞參數(shù)
前臺在上一篇,下一篇處調(diào)用:
<?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'] = "下一篇:沒有了 "; }}代碼經(jīng)測試可用
希望本文所述對大家PHP程序設(shè)計有所幫助。
新聞熱點
疑難解答
圖片精選