phpcodeigniterpaginationlimitquery-builder

How to set the LIMIT and OFFSET clauses conditionally with CodeIgniter's query builder


This is my LoteModel method:

public function selecionar($where = NULL, $limit = NULL, $order_by = NULL)
{
    if (!is_null($where)) {
        $this->db->where($where);
    }
    if (!is_null($limit)) {
        $this->db->limit($limit);
    }
    if (!is_null($order_by)) {
        $this->db->order_by($order_by);
    }
    
    return $this->db->get(_LOTE_);//_LOTE_ is a constant for my table name
}

and I call it like this:

$config['per_page'] = '5';
    
$limite = $config['per_page'] . ',' . $this->uri->segment(3); //the segment is ok, I receive it
    
$lotes = $this->LoteModel->selecionar(array('quadra_id' => $quadra_id, 'lote_status' => 1), $limite, 'lote_endereco'); 

I have checked the SQL result for that query:

SELECT * FROM (`realestate_lote`) WHERE `quadra_id` = '1' AND `lote_status` = 1 ORDER BY `lote_endereco` 

The thing is, it's not generating my LIMIT, it will only work if I add it to the LoteModel method.

I'm working with pagination.


Solution

  • You can't pass a string like "5,1" to CI's ActiveRecord limit function. The function requires two parameters.

    Split the limit string by "," and pass the two values like the example below.

    $limit = explode(',', $limit);
    $this->db->limit($limit[0], $limit[1]);
    

    Hope this helps...