如何在Codeigniter中获取和返回记录总数的记录

时间:2019-02-13 02:02:11

标签: php codeigniter

我正在使用codeigniter使用rest api,我想获取记录+总记录+每页记录,但不适用于我 这是我在控制器中的功能

<?php 
public function search_shop()
{
    $users['rec'] = $this->Model_users->find_shop($_POST);
    if($users['rec']!="")
        {
            $responseJSON = array("Status" => true,"Result" => $users['rec']);
            header("content-type:application/json");
            $response = json_encode($responseJSON);
            echo $response; 
        }
        else
            {
                $responseJSON = array("Status" => false,"Message" => "There is no matching record");
                header("content-type:application/json");
                $response = json_encode($responseJSON);
                echo $response; 
            }   
}

这是我在模型中的“ find_shop”函数,如何获取具有记录总数和每页记录数的所有记录?

public function find_shop()
{       
        $add_data['page_number'] = ($this->input->post('page_number') && !empty($this->input->post('page_number'))) ? $this->input->post('page_number') : NULL;

        $add_data['search'] = ($this->input->post('search') && !empty($this->input->post('search'))) ? $this->input->post('search') : NULL;     

        $records="10";  
        $mins="10";
        if($add_data['page_number']=="" || $add_data['page_number']=="0" || $add_data['page_number']=="1")
            {
                $starting_row="0";
                $last_row="10";
            }
        else
            {
                $last_row="9";
                $cd="1";
                $lim="10";
                $starting_row=$add_data['page_number']*$lim-$last_row-$cd;
                $last_row=$add_data['page_number']*$records-$cd;
            }
        $this->db->select('*');
        $this->db->from('shop s');
        $this->db->like('shop_name',$add_data['search']);
        $this->db->or_like('city',$add_data['search']);
        $this->db->limit($last_row,$starting_row);      
        $query = $this->db->get();
        if ( $query->num_rows() > 0 )
            {
                $row = $query->result_array();
                return $row;
                return $query->num_rows;
            }
        else
            {
                return false;
            }
    }
?>

2 个答案:

答案 0 :(得分:0)

尝试一下,希望对您有帮助
在Controller中,请在模型相关更改后对此进行测试

required

在模型中,返回中有错误,您不能同时执行两次返回

$users = array();
$users = $this->Model_users->find_shop($_POST);
echo'<pre>';print_r($users);die;

答案 1 :(得分:0)

按以下方式更改您的if条件:

        $records="10";  // This is records per page showing
        if ($add_data['page_number']=="" || $add_data['page_number']=="0" || $add_data['page_number']=="1")
        {
            $starting_row="0";
        } else {
            $starting_row = ($add_data['page_number'] - 1) * $records;            
        }

您需要设置查询的限制和偏移量。例如:limit 0,10:这将显示前10条记录。这里0是起点,10是要显示的记录长度。 10将始终与您显示10条记录相同。限制10、10:它将显示从10到19的记录。希望它消除您的疑问。