Codeigniter get number of row from search query

hairynuggets picture hairynuggets · Nov 1, 2011 · Viewed 7.6k times · Source

I have a query in my controller which searches for the term/keyword that is in the url.

Example /search/keyword

Then through my controller I perform the search doing:

   $viewdata['search_results'] = 
$this->Search_model->search(strtolower($this->uri->segment(2)),$limit,$offset);

then I check the database from my model like so:

    function search($searchquery, $limit, $offset) {

        $this->db->from('content');
        $this->db->like('title', $searchquery);
        $this->db->or_like('content', $searchquery);
        $query = $this->db->limit($limit, $offset)->get();

        $results = Array();
        foreach ($query->result() as $row) {


            $results[] = Array(

                'title' => '<a href="' . base_url() . $row->anchor_url . ' ">' . strip_tags($row->title) . '</a>',
                'link' =>  base_url() . $row->anchor_url,
                'text' => str_ireplace($searchquery, '<b>' . $searchquery . '</b>', strip_tags(neatest_trim($row->content,220,$searchquery,120,120)))
            );
        }
        return $results;
    }

}

I would like to know how I can return the number of rows found in my search result to the controller. I will then use the count of rows found for pagination.

How can I get the row count into the controller????

Answer

evan picture evan · Nov 1, 2011

You can add a function in your model that returns the count and call that.

Example:

// model
public function getAffectedRows()
{
    return $this->db->affected_rows();
}

...

// controller
$this->Search_model->doQuery();
$numRows = $this->Search_model->getAffectedRows();