How to pass data from Model to View - BOOKC -->

How to pass data from Model to View

Monday, August 14, 2017

In this article, I'm trying to explain you how to work with models, views and controllers to fetch data from the model. During this process, first the data is fetched from model by controller and then it passes the data to the view. The flow is going on according to the MVC architecture and no direct fetching from model by the view. To do this, we need to create 3 files. In my case I have created and named them as User_model, user_view and User_data(controller).

What will I do?

I will code to pass some details of a user stored in User_model, to the user_view.

First take the model file; User_model. We need to include the user data as an Array in this file. Then later we can use them by calling the keys in the view file. A function called  return_data is used to return the values in the array. Here, ID and Usernames are keys and 123 and Salitha are values.


class User_model extends CI_Model {
  public function return_data() {
return ["ID"=>"123","Username"=>"Salitha"];


Now our logic is ok. Next we will code the controller file; User_data. I create the index function to load the model because that index function is always called as  default. First the model should be loaded. Then I have used the data variable to store the values in array called userArray. For that I will assign the loading the return_data function from the model. After that this data is passed to the view and it will be loaded. The assigned variable should be passed in the view. Otherwise it will not work.


class User_data extends CI_Controller {
  public function index() {
    $data["userArray"] = $this->user_model->return_data();


Now we have to decide the way to display these data. I'll use a HTML table to do this using table rows.
user_view :

<!DOCTYPE html>
<title>User Details</title>
    <td><?= $userArray["ID"];?></td>
    <td><?= $userArray["Username"];?></td>

The  above highlighted part is relevant too the fetching of suitable data according to the keys. For ID and Username, the values stored for the keys in the userArray are fetched.

Now we can call the index function in controller to get the output.



You will have a basic understanding of how to fetch data from a model and pass to the view now. Try this and if you have issues, comment below.
Good Luck!