0
votes

I have a controller in codeigniter pages.php

class Pages extends CI_Controller {

    public function view($page = 'home')
    {
        $this->load->view('header');
        echo("<br>");
        $this->load->model("math");
        echo $this->math->add(1,2);
    }
}

The model: math.php

class math extends CI_Controller
{
    public function add($val1,$val2){
        return $val1+$val2;
    }
}

The view: header.php

<html>
<head>
    <title>fashion and style</title>
</head>
<body>
<?php
    echo("this is the header");
?>

As per the controller the code should output:

this is the header

number

but i get the output like:

number this is the header

Why?

2
class math extends CI_Controller ==> CI_Model is it spelling mistake!! just wanted to know...Gaurav Mehra
Well anything u will echo out in controller or model will appear before any view as the view is rendered in index.php and displayed in the final step.Gaurav Mehra
@GauravMehra how can you say that, is it in the documentation, please share a linkbhawin

2 Answers

2
votes

If you will echo the string from the codeignitor controller directly, it will render the string before rendering the loaded views. If you want to do so, you can try like-

$str = $this->math->add(1,2);
$this->output->append_output($str);

Then your controller will look like-

class Pages extends CI_Controller {

    public function view($page = 'home')
    {
        $this->load->view('header');
        $this->load->model("math");
        $str = "<br>".$this->math->add(1,2);
        $this->output->append_output($str);
    }
}

Hope this will help.

0
votes

Try this:

Controller:

class Pages extends CI_Controller {

    public function view($page = 'home')
    {
        $this->load->model("math_model");
        $data['number'] = $this->math_model->add(1,2);

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

    }
}

the model math_model.php

Model:

class Math_model extends CI_Model
{
    public function add($val1,$val2){
        return $val1+$val2;
    }
}

the view header.php

<html>
<head>
    <title>fashion and style</title>
</head>
<body>
<?php
    echo("this is the header");
?>
echo("<br>");
<?php 
        echo $number;
?>
</body>
</html>

For model details have a look here https://www.codeigniter.com/user_guide/general/models.html

For views have a look here https://www.codeigniter.com/user_guide/general/views.html