Zubdev
Zubdev

Reputation: 164

Get next and previous row from record set

I am trying to retrieve the next row in my database using Codeigniter's active record.

Model

public function getNextRow()
{
    $this->db->where('id', 1);
    $this->db->limit(1);
    $query = $this->db->get('portfolio_shots');
    return $query->next_row();
}

Controller

public function test()
{
    $nxt = $this->Portfolio_model->getNextRow();
    echo $nxt->id;
}

Output

Why am I getting the error

"Trying to get property 'id' of non-object"

enter image description here

Upvotes: 1

Views: 719

Answers (1)

Vickel
Vickel

Reputation: 7997

next_row() returns:

Next row of result set, or NULL if it doesn’t exist:

so, if there is no next result set, you get the error

"Trying to get property of non-object"

because $nxt is null and not a result set and therefore you cannot $nxt->id;

you get into this situation, because your result set is limited by your query to 1 row only (therefore no more rows)

anyway you can handle this in your model (removing limits):

public function getNextRow()
{
    $query = $this->db->get('portfolio_shots');
    return $query->next_row();
}

and in the controller (handle case if last row was reached):

public function test()
{
    $nxt = $this->Portfolio_model->getNextRow();
    if($nxt){
      $nxt->id;
    }else{
      echo 'EOF';
    }
}

Upvotes: 1

Related Questions