1

Could you please tell me how my model,controller and view should look like if I want to pass the following variable data($amount1, $amount2, $amount3) to my view file via controller from my model.

 case 1: $amount1=100;

 case 2: $amount2=500;

 case 3: $amount3=1000;

I want to have the variables in a way that I don't have to echo them in any { } example:

 foreach ($records as $row){ $i++; ?>
 // I don't want to echo those inside in this. 
//   I want to echo it like this way- <? echo $amount1;?>
 }

Thanks in Advance :)

2 Answers 2

3

If you pass an array of data from your controller to your view you can access each element as a variable in the view. Here is an example of what I mean:

model:

class Model extends CI_Model
{
    public function get_data()
    {
        $data = array(
            'amount1' => 100,
            'amount2' => 500,
            'amount3' => 1000,
        );

        return $data;
    }
}

controller:

class Controller extends CI_Controller
{
    public function index()
    {
        // get data from model
        $data = $this->model->get_data();

        // load view
        $this->load->view('view', $data);
    }
}

view:

<h1><?php echo $amount1; ?></h2>
<p><?php echo $amount2; ?></p>
<!-- etc... -->
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your reply...:) actually i am getting the variables after generating some database query... thats why I wanted to send it from my model. .. :) thanks
0

I have found a solution myself. I just wanted to share so that it can help others. So here it is..

Your model should look like following :

function net_income(){
    $data['amount1']=50;
    $data['amount2']=100;

    return json_encode($data);
    } 

Your controller:

 function add(){

    $this->load->model('mod_net_income');
    $json = $this->mod_net_income->net_income();

    $obj = json_decode($json);
    $data['amount1']= $obj->{'amount1'};  

           $this->load->view('your_viewfile_name',$data);

    }

And then in your view file: just

      <? echo "$amount" ; ?>

Thanks :)

1 Comment

There is no need to encode the data to pass it from the model to the controller. You could just return the $data array and then pass it directly to the view. I have updated my answer with a better example. Also, is you are just echoing a variable there is no need to wrap it in double quotes. echo $amount; will suffice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.