banner image
Sedang Dalam Perbaikan

How to pass data from Model to View



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.

<?php

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.

<?php

class User_data extends CI_Controller {
  public function index() {
    $this->load->model('user_model');
    $data["userArray"] = $this->user_model->return_data();
    $this->load->view("user_view",$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>
<html>
<head>
<title>User Details</title>
</head>
<body>
<table>
  <tr>
    <th>ID</th>
    <th>Username</th>
  </tr>
  <tr>
    <td><?= $userArray["ID"];?></td>
    <td><?= $userArray["Username"];?></td>
  </tr>
</table>
</body>
</html>

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.

http://localhost/PHPProjects/CITEST/index.php/user_data

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!

















How to pass data from Model to View How to pass data from Model to View Reviewed by DAL on August 14, 2017 Rating: 5

No comments:

Powered by Blogger.