Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

php - Fetch data from database in codeigniter

I have 2 cases where i am fetching the entire data and total number of rows of a same table in codeigniter, I wish to know that is there a way through which i can fetch total number of rows, entire data and 3 latest inserted records from the same table through one code

Controller code for both cases is as given below (although i am applying it for each case seperately with different parameters)

public function dashboard()
    {
        $data['instant_req'] = $this->admin_model->getreq();
        $this->load->view('admin/dashboard',$data);
    }

1) to fetch the entire data from a table in codeigniter

Model Code

public function getreq()
    {
        $this->db->where('status','pending');
        $query=$this->db->get('instanthire');
        return $query->result();
    }

View Code

foreach ($instant_req as $perreq) 
    {
        echo $perreq->fullname;
        echo "<br>";
    }

2) to fetch number of rows from a table in codeigniter

public function getreq()
    {
        $this->db->where('status','pending');
        $query=$this->db->get('instanthire');
        return $query->num_rows();
    }

View Code

echo $instant_req;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can make only one function that gives you the all data at once total number of rows, entire data and 3 latest inserted records

for example in the model

public function getreq()
{
    $this->db->where('status','pending');
    $query=$this->db->get('instanthire');
    $result=$query->result();
    $num_rows=$query->num_rows();
    $last_three_record=array_slice($result,-3,3,true);
    return array("all_data"=>$result,"num_rows"=>$num_rows,"last_three"=>$last_three_record);
}

in controller dashboard function

public function dashboard()
{
    $result = $this->admin_model->getreq();
    $this->load->view('admin/dashboard',$result);
}

in view

foreach ($all_data as $perreq) 
{
    echo $perreq->fullname;
    echo "<br>";
}
//latest three record
foreach ($last_three as $perreq) 
{
    echo $perreq->fullname;
    echo "<br>";
}
//total count
echo $num_rows;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...