Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT with LIMIT in Codeigniter

I have a site develop in Codeigniter, and in my model I have a function like this:

function nationList($limit=null, $start=null) {
    if ($this->session->userdata('language')=="it")
    $this->db->select('nation.id, nation.name_it as name');
    if ($this->session->userdata('language')=="en")
    $this->db->select('nation.id, nation.name_en as name');
    $this->db->from('nation');
    $this->db->order_by("name", "asc");
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    $nation = array();
    foreach ($query->result() as $row)
        array_push($nation, $row);

    return $nation;     
}

And if into my controller I call the function without limit and start doesn't return result like this:

$data["nationlist"] = $this->Nation_model->nationList();

Instead if I set limit and start works! If limit and start are null, Why doesn't return result? I don't want to make a second function or a control if limit and start are null. How can I solve this when limit and start are null without a control or a second function to make useful the code and more efficient?

like image 211
Alessandro Minoccheri Avatar asked Jan 09 '13 08:01

Alessandro Minoccheri


2 Answers

Try this...

function nationList($limit=null, $start=null) {
    if ($this->session->userdata('language') == "it") {
        $this->db->select('nation.id, nation.name_it as name');
    }

    if ($this->session->userdata('language') == "en") {
        $this->db->select('nation.id, nation.name_en as name');
    }

    $this->db->from('nation');
    $this->db->order_by("name", "asc");

    if ($limit != '' && $start != '') {
       $this->db->limit($limit, $start);
    }
    $query  = $this->db->get();

    $nation = array();
    foreach ($query->result() as $row) {
        array_push($nation, $row);
    }

    return $nation;     
}
like image 51
Deepu Avatar answered Nov 16 '22 12:11

Deepu


For further visitors:

// Executes: SELECT * FROM mytable LIMIT 10 OFFSET 20
// get([$table = ''[, $limit = NULL[, $offset = NULL]]])
$query = $this->db->get('mytable', 10, 20);

// get_where sample, 
$query = $this->db->get_where('mytable', array('id' => $id), 10, 20);

// Produces: LIMIT 10
$this->db->limit(10);  

// Produces: LIMIT 10 OFFSET 20
// limit($value[, $offset = 0])
$this->db->limit(10, 20);
like image 26
javier_domenech Avatar answered Nov 16 '22 11:11

javier_domenech