[SOLVED] get next & previous id record in database on Yii


I need next & previous id record in database on Yii framework to make navigation buttons next and back ?


I made a function to get those ids your looking for. I suggest you to declare it in the model:

public static function getNextOrPrevId($currentId, $nextOrPrev)
    if($nextOrPrev == "prev")
       $order="id DESC";
    if($nextOrPrev == "next")
       $order="id ASC";

       array('select'=>'id', 'order'=>$order)

    foreach($records as $i=>$r)
       if($r->id == $currentId)
          return isset($records[$i+1]->id) ? $records[$i+1]->id : NULL;

    return NULL;

So to use it all you have to do do is this:

YourModel::getNextOrPrevId($id /*(current id)*/, "prev" /*(or "next")*/); 

It will return the corresponding id of the next or previous record.

I didn’t test it, so give it a try and if something goes wrong please let me know.

Answered By – Alfredo Castaneda Garcia

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *