Codeigniter将实际的行数(不限)从模型传递给控制器

时间:2014-10-21 16:06:33

标签: php mysql codeigniter

只想使用Codeigniter显示分页搜索结果和结果数(例如"找到17个结果")。一切正常,但它显示"找到5个结果"相反"找到17个结果"。请检查下面的代码并帮助我将实际的行数(不限)从模型传递给控制器​​。

我的模特:

public function did_get($city, $limit, $offset) { 

    $this->db->select('*');
    $this->db->from('table');

    $this->db->where('city', $city); 

    $query = $this->db->get();

    $this->db->limit($limit, $offset);   

    if ($query && $query->num_rows() > 0) {

        return $query->result_array();
    } else {
        return false;
    }
}

我的控制器:

            if ($this->model_get->did_get($city, $limit, $offset)) {

            $data["count"] = $this->model_get->did_get_count($city);

            $data["results"] = $this->model_get->did_get($city, $limit, $offset);

            $this->load->view("view_results",$data);                    

3 个答案:

答案 0 :(得分:2)

您可以删除限制条款并获取实际计数

public function did_get($city, $limit=0, $offset=0) 
{ 

    $this->db->select('*');
    $this->db->from('table');

    $this->db->where('city', $city); 

    $query = $this->db->get();

    //set limit only if $limit and $offset are provided
    if($limit && $offset) $this->db->limit($limit, $offset);   

    if ($query && $query->num_rows() > 0) 
    {
        return $query->result_array();
    } 
    else 
    {
        return false;
    }
}

和您的控制器

$data["results"] = $this->model_get->did_get($city);
$data['count'] = count($data["results"]);              
$this->load->view("view_results",$data); 

答案 1 :(得分:1)

我无法对此进行测试,但请检查以下内容:

public function did_get($city, $limit, $offset) { 

    $this->db->select('*');
    $this->db->from('table');

    $this->db->where('city', $city); 

    $query = $this->db->get();

    $array["count"] = $query->num_rows();

    $this->db->limit($limit, $offset);   

    if ($query && $query->num_rows() > 0) {

        $array["results"] = $query->result_array();
    } else {
        $array["results"] = false;
    }
    return $array;
}

然后,在您的控制器中,您可以轻松访问数据:

$limit = 5;

$this->load->view("view_results",$this->model_get->did_get($city, $limit, $offset)); 

答案 2 :(得分:1)

由于你需要为分页保留limit子句,为什么不返回带有这两个值的数组呢?

你的模特

public function did_get($city, $limit=0, $offset=0) 
{ 

    $this->db->select('*');
    $this->db->from('table');

    $this->db->where('city', $city); 

    $query = $this->db->get();

    $count = count($query->result_array());

    //set limit only if $limit and $offset are provided
    if($limit && $offset) $this->db->limit($limit, $offset);   

    if ($query && $query->num_rows() > 0) 
    {
        $rows = $query->result_array();
        $results = array (
            "count" => $count,
            "rows" => $rows
        );
        return $results;
    } 
    else 
    {
        return false;
    }
}

您的控制器

$limit = 5;

$results = $this->model_get->did_get($city, $limit, $offset);

$data['count'] = $results["count"];

$data['results'] = $results["rows"];              

$this->load->view("view_results",$data);