在 Codeigniter 中使用 LIMIT 进行选择

2022-08-30 20:37:12

我在Codeigniter中有一个网站开发,在我的模型中,我有一个这样的功能:

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

如果进入我的控制器,我无限制地调用函数,并且start不会返回如下结果:

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

相反,如果我设置限制并开始工作!如果 limit 和 start 为 null,为什么不返回结果?我不想做第二个函数或控件,如果限制和开始为空。当限制和启动为空而没有控件或第二个函数以使代码有用且更有效时,我该如何解决这个问题?


答案 1

试试这个...

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

答案 2

对于其他访客:

// 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);

推荐