VeenZ VeenZ - 1 year ago 133
MySQL Question

Codeigniter count too slow - pagination

I try to make a search using codeigniter faster , i use the pagination library and i have to count the records returned from the query on a table wich contained more than 1.2 millions of records ... the num_rows() function is very slow ( take approximately 3 secondes )

public function search()


$data = array();

$query = $this->input->get('query');
$filter = $this->input->get('f');
$hd = $this->input->get('hd');

if($hd == 'true'):

$request = urldecode($query);

$where = "MATCH (name,tags) AGAINST ('".$request."' IN BOOLEAN MODE)";

$get_vars = $this->input->get();

if(is_array($get_vars) && ($this->input->get('query')) ):
$config['suffix'] = '?'.http_build_query($get_vars,'', '&');

$config['base_url'] = base_url('search');
$config['per_page'] = 8;
$config['num_links'] = 8;
$config['full_tag_open'] = '<div class="pagination"><ul>';
$config['full_tag_close'] = '</ul></div><!--pagination-->';
$config['first_link'] = '&laquo; First';
$config['first_tag_open'] = '<li class="prev page">';
$config['first_tag_close'] = '</li>';
$config['last_link'] = 'Last &raquo;';
$config['last_tag_open'] = '<li class="next page">';
$config['last_tag_close'] = '</li>';
$config['next_link'] = 'Suivant &rarr;';
$config['next_tag_open'] = '<li class="next page">';
$config['next_tag_close'] = '</li>';
$config['prev_link'] = '&larr; Précédent';
$config['prev_tag_open'] = '<li class="prev page">';
$config['prev_tag_close'] = '</li>';
$config['cur_tag_open'] = '<li class="active"><a href="">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li class="page">';
$config['num_tag_close'] = '</li>';

$query = clone $this->db;
$config['total_rows'] = $query->get('videos')->num_rows();
$config['segment'] = $this->uri->segment(2);

$data['results'] = $this->db->get('videos',$config['per_page'],$this->uri->segment(2))->result();


Any solutions ?

Answer Source

As the comments from @MonkeyZeus suggests, performance will improve by using the SQL count() function. Codeigniter provides this through the Query Builder function count_all_results($table = '', $reset = TRUE).

The function will take into account any restrictors you have put in place e.g. where, or_where, like, etc.

Change this

$query = clone $this->db;
$config['total_rows'] = $query->get('videos')->num_rows(); 

to this

//next line is not needed because the query will not be reset by the row count
//$query = clone $this->db;
$config['total_rows'] = $this->db->count_all_results('videos', FALSE); 

I'd be interested in knowing how execution time changes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download