[SOLVED] Codeigniter loop to chunk query only ever gets the first chunk of rows?


I’m trying to get a large amount of data by grabbing it in chunks from the database and writing it to CSV. For some reason the code below is only writing the first chunk (2000 rows) to CSV. I have my $chunk and $limit variables writing to a text file, and those are going through the loop and writing out the correct values. So why isn’t $result=$this->db->get(‘tblProgram’, $chunk, $offset)->result_array(); grabbing the next chunks?

Can you not run $this->db->get(‘tblProgram’, $chunk, $offset)->result_array(); multiple times with different offsets? How else would I loop through the results?

I can confirm that I have more than 200k rows returned from the query, and that if I set chunk to something different, I’m still only getting the first chunk returned.

//Get rows from tblTrees based on criteria set in options array in downloadable format
    public function get_download_tree_data($options=array(), $rand=""){

        $this->db->order_by('tblTrees.id', 'ASC');

       // $allResults=$this->db->count_all_results('tblProgram', false);
        while (($offset<$allResults)) {
            $temptxt=$chunk." ".$offset."\n";

            $result=$this->db->get('tblProgram', $chunk, $offset)->result_array();
            foreach ($result as $row) {
                fputcsv($tree_handle, $row);
            return array('resultCount'=>$allResults);



Looks like calling the get method resets your model:

    public function get($table = '', $limit = NULL, $offset = NULL)
        if ($table !== '')

        if ( ! empty($limit))
            $this->limit($limit, $offset);

        $result = $this->query($this->_compile_select());
        return $result;

I’d imagine this is the case of any version of ci.

Answered By – Kisaragi

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *