Codeigniter, PHP

Codeigniter: How to Pass Data to View

Codeigniter | Controller | Framework | Mvc | PHP | View



This entry is part 3 of 8 in the series Learn Codeigniter

In Previous Tutorial we have discussed about basic concept of controller & view, but we haven’t seen how to pass data to view from codeigniter controller. That’s what we are going to learn now. Let’s say we want to pass title and content to a view so it can display data according to what we pass from controller.

Follow Steps to Pass Data to View in Codeigniter

First open Home controller and modify the about function to pass data to view (about view) and then we create about view as well (Remember i gave you as homework. i hope you completed).


Create new file in view directory and name it about.php and put following code in it.

$this->load->view() function accepts 2 arguments, second one is optional. first argument is name of the view without extension. and second argument is array containing key value pairs. if second argument is passed then all keys will be converted into variable names and they will occupy the values which are present in that array like in our example, 2 variables will be loaded in view file. First will be $title which has string (‘About Us’) in its value and second will be $content which contains string (‘About My Website…….’) in its value. so when we navigate to URL (http://localhost:8888/ci/index.php/home/about), we will get result like this:

CodeIgniter Pass Data to View

We can also change the index function to pass data to view but this time we use same view cause we want the look to be same.

we can see that we loaded same about view we created above and it will load data that has been passed by index function so result will be:

The advantage of working with MVC architecture is that we can use same view to load different data in it on different pages if the look is unchanged.

So in short a method in controller can be a page of our site and controller can represent the whole website. But we can add multiple controllers in a single website. controllers and methods makes our URL of the website pages which makes it more SEO friendly. So that’s it for now and we will cover models in next tutorial.

Thank you :-) .

Series Navigation<< Codeigniter Model: How to fetch Data From DatabaseCodeigniter create helper >>

Bookmark Link using: bookmark at folkd