Abudayah Abudayah - 1 year ago 115
PHP Question

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 ?

Answer Source

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 $records[$i+1]->id ? $records[$i+1]->id : NULL;

    return NULL;

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

YourModel::getPrevOrNextId($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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download