php 在 Codeigniter 中使用 LIMIT 进行选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14231170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:53:56  来源:igfitidea点击:

SELECT with LIMIT in Codeigniter

phpsqlcodeigniter

提问by Alessandro Minoccheri

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

我有一个在 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;     
}

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

如果进入我的控制器,我会无限制地调用该函数,而 start 不会返回这样的结果:

$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?

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

回答by Deepu

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

回答by vivoconunxino

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