Edward
Edward

Reputation: 3091

Codeigniter alter query

I'm building a search function and i'm pretty sure the proper way is to only get the # of results you want to display, in my case 20 per page. I'm wondering what is the best way for me to change that select('*') statement to return the total # of results select('count(*)'); and rerun the exact same query?

$this->db->select('*');
$this->db->from('MyTable');
$this->db->where('some complex conditions');
$this->db->join('a bunch of joins);
$this->db->limit('20','$page*20');

to

$this->db->select('count(*)');
/* reuse this part */
$this->db->from('MyTable');
$this->db->where('some complex conditions');
$this->db->join('a bunch of joins);
/* reuse this part */

run first query

$q1 = $this->db->get()->result_array();

run second query

$q2 = $this->db->get('q1 with different select')->result_array();

   array_merge($q1,$q2);

Upvotes: 0

Views: 96

Answers (2)

Amrit Gautam
Amrit Gautam

Reputation: 85

You Can also do this way

    // For required output   
    $this->db->select('');
    $this->db->from();
    $this->db->join();
    $this->db->order_by();
    $this->db->limit((int)$page['limit'],(int)$page['start']);
    $list['list'] = $result->result();

    // To count total number of rows
    $this->db->select('');
    $this->db->from();
    $this->db->join();
    $this->db->order_by();
    $result_total = $this->db->get();
    $list['list'] = $result->result();

    $list['total'] = $result_total->num_rows();
    return $list;
    }

Upvotes: 1

ahpan
ahpan

Reputation: 177

Codeigniter actually has a pagination helper that is pretty useful: https://ellislab.com/codeIgniter/user-guide/libraries/pagination.html

If you don't prefer to use it, you can pass in the current query number that you are at to the controller through the url.

For example www.example.com/page/search/40. Where the query will then take that number to use for the limit.

Upvotes: 1

Related Questions