php如何?上一篇下一篇

來源:互聯網
上載者:User

網站開發過程中經常遇見上一篇下一篇問題的處理,今天剛好在做一個項目的時候也遇到了,這個是對自己以前方法的改進,可能會存在沒有考慮到的問題,請大家可以在這個基礎上改進

首先,當我們去訪問一篇文章的時候需要在路由中傳遞這個文章的id以及這篇文章所屬的欄目,id,cateid

要保證顯示的上一篇和下一篇文章和當前文章是同一個欄目下的文章,會有一個方法顯示某一篇文章的具體資訊

例如這樣:

// 話題內容頁public function index(){    $topics = D('TopartView');    $cateid = I('cateid');    $arid = I('arid');    // 調用分頁方法(上一頁下一頁)    $this->pages($arid,$cateid);    $content = $topics->where(array('id'=>$arid))->find();    if($content) {        // 瀏覽次數        $topics->where(array('id'=>$arid))->setInc('click',1);        $this->assign('content',$content);        $this->display();    }else {        $this->error('非法操作',U('account/login'));    }}

可以看到這個方法裡面也接收了id,cateid兩個參數   ,有一個方法pages,這個方法就是調用上一篇下一篇文章的

具體實現方法如下:

/* * $id  當前文章id * $cateid 當前文章所屬欄目id * */public function pages($id,$cateid) {    $topic = D('Topic');    // 下一頁查詢條件    $where = array(        'id' => array('gt',$id),        'cateid' => array('eq',$cateid),    );    $next_topic = $topic->order('id asc')->where($where)->limit(1)->select();    if($next_topic) {        $next_topic = $next_topic[0];    }else {        $next_topic = null;    }    // 下一篇查詢條件    $where = array(        'id' => array('lt',$id),        'cateid' => array('eq',$cateid),    );    $prev_topic = $topic->order('id desc')->where($where)->limit(1)->select();    if($prev_topic) {        $prev_topic = $prev_topic[0];    }else {        $prev_topic = null;    }    $this->assign('prev_topic',$prev_topic);    $this->assign('next_topic',$next_topic);}


這個方法的核心在於where條件的使用,顯示下一頁的時候必須保證id是要大於當前文章的id,同樣上一篇的id需要小於當前文章的id,並且這裡還有一個需要注意的問題是每一篇文章並不是連續的,有的文章可能被刪除了,所以在查詢的時候記得排序一下,查詢下一篇的時候就是按照升序,查詢下一篇的時候就是按照降序,然後就是資料的分配了,整個過程就是這樣



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.