views:

383

answers:

2

Hi, I bet this is easy but been trying for a while and can't seem to get it to work. Basically I am setting up pagination and in the model below I want to pass $total_rows to my controller so I can add it to the config like so '$config['total_rows'] = $total_rows;'.

function get_timeline_filter($per_page, $offset, $source) 
    {
        $this->db->where('source', $source);
        $this->db->order_by("date", "desc");
        $q = $this->db->get('timeline', $per_page, $offset);
        $total_rows = $this->db->count_all_results();

        if($q->num_rows() >0) 
        {
            foreach ($q->result() as $row) 
            {
                $data[] = $row;                 
            }
            return $data;
        }

    }

I understand how to pass things form the Controller to the model using $this->example_model->example($something); but not sure how to get a variable from the model?

A: 

Hi,

I think changing your config in runtime is not good ideia, but I have 3 ways for you get the $total_rows value in your controller.

ideia 1. You can store the value of $total_rows in the session

ideia 2. pass the variable by reference (using &$total_rows in the function definition ex:

function get_timeline_filter($per_page, $offset, $source, &$total_rows) 

read this: http://php.net/manual/en/language.references.pass.php

in your controller you call:

$total_rows=0;
$result=$this->model_name->get_timeline_filter($per_page, $offset, $source, &$total_rows);

ideia 3. return the value from the function ex:

(...)

if($q->num_rows() >0) 
{
    foreach ($q->result() as $row) 
    {
        $data[] = $row;                 
    }
    return $data;
}

$final_data['total_rows']=$total_rows;
$final_data['data']=$data;

return $final_data;

Regards,
Pedro

Pedro
Hi Pedro, I don't seem to be able to implement the code. I am fairly new to PHP and Codeigniter. If I go with idea 2, do I just replace `function get_timeline_filter($per_page, $offset, $source)` with `function get_timeline_filter($per_page, $offset, $source, ` I have tried it but I just get an errors.Model error = `Message: Missing argument 4 for Timeline_model::get_timeline_filter()`Controller error = `Message: Undefined variable: total_rows`
Craig Ward
Hi Craig, I put one better description in ideia 2. Please take a look and if don't understand please feel free to ask more info
Pedro
Number 2 worked perfectly, excellent :)
Craig Ward
A: 

Set $total_rows as a class variable in the model and access it from your controller as if it were any other class variable

$total = $this->dbmodelname->total_rows;
coolgeek