简体   繁体   中英

How do I get the number of rows after a db query in Codeigniter?

I managed to get rows of data returned for doing a specific search but I can't get the number of rows that have been found. Here is my code

My Controller

function searchdata(){
    $result = $this->posts->search($_POST['searchterm']);
    $data['posts']= $result['rows'];
    $data['num_results']= $result['num_rows']; // num_rows is the number of rows returned from a search 

    $this-> load-> view('results_index',$data);
}

My model

function get_search($keyword)
{
$q = $this-> db-> select('*')-> from ('blog');
$q= $this->db->like('title',$keyword);
$q= $this->db->or_like('description',$keyword);

$results['rows']= $q-> get()-> result();
//$results['num_rows']= $q-> num_rows(); <--- this doesn't work, invalid method, commented out
return $results;

}

If it helps, this https://www.codeigniter.com/user_guide/database/results.html might be able to help you. I thought it would

Thanks guy.

The problem is that your trying to execute num_rows on a non CI-DB Object, you're executing the num_rows over an array and that doesnt exist, you need to call the num_rows over the object that return the this->db->get().

I would change it to this way:

function get_search($keyword)
{
$this-> db-> select('*')-> from ('blog');
$this->db->like('title',$keyword);
$this->db->or_like('description',$keyword);

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

$results['num_rows']= $q->num_rows(); 
$results['rows'] = $q->result();
return $results;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM