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).

Home Controller (application/controllers/home.php)

PHP

8

9

10

11

12

13

14

15

functionabout()

{

$data["title"]="About Us";

$data["content"]="About My Website.......";

$this->load->view("about",$data);

}

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

About View (application/views/about.php)

XHTML

1

2

3

4

5

6

7

8

9

10

11

12

13

<html>

<head>

<title>My Website : <?=$title?></title>

</head>

<body>

<h1>My Website : <?=$title?></h1>

<p>

<?php

echo$content;

?>

</p>

</body>

</html>

$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:

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.

Home Controller (application/controller/home.php

PHP

1

2

3

4

5

6

7

8

functionindex()

{

$data["title"]="Home";

$data["content"]="Welcome to My Website.......";

$this->load->view("about",$data);

}

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.