Get next and previous row from record set

倖福魔咒の 提交于 2020-01-05 03:42:47

问题


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"


回答1:


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';
    }
}


来源:https://stackoverflow.com/questions/59339373/get-next-and-previous-row-from-record-set

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!