5

I have a view which comport a table of data, this data is generated on a model. How can I call this model in my view to be posted on my view...? That's the Equivalent of what I want to do with codeIgniter on php :

while($row = mysql_fetch_array($requet))
      {
// code of displaying my data;
      }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Fatim
  • 155
  • 3
  • 3
  • 13

5 Answers5

19

try using $CI =& get_instance()

then load your model like this:

$CI->load->model('someModel')

then call your model function like this:

$result = $CI->someModel->somefunction()

then display using foreach

foreach($result as $row){ $row->somecolumnName }

Mohammed Sufian
  • 1,743
  • 6
  • 35
  • 62
3

i called model method like this.

<?php
$CI =& get_instance();
$CI->load->model('MyModel');
$result= $CI->MyModel->MyMethod($parameter)->result_array();        
  foreach($result as $row){ 
         echo $row['column_name'];                      
    }
?>
Engr Saddam Zardari
  • 1,057
  • 1
  • 14
  • 27
2

I think it is not a good idea to call a model directly from the view.

Your controller must get data from the model then send it to your view

$this->load->model('my_model');
$my_data['my_array'] = $this->my_model->get_my_data();
$this->load->view('your_view', $my_data);

In your view use it like this

foreach($my_array as $item){
    echo $item;
}
Jice06
  • 221
  • 2
  • 4
  • In your view use it like this foreach($my_array as $item){ } – Jice06 Jan 15 '14 at 14:56
  • There are pages that you may require to run directly in the model, that is why he is asking. For instance, sidebar that needs to be on each page. Getting values from every controller of the page you want to display may not be effective – kimoduor Sep 28 '21 at 13:29
1

First Model interacts withe the database.Then load the model and access relevant function in your controller.Finally load the data to view from the controller.That's it...you can show the data simply in a foreach loop.

CodeCanyon
  • 929
  • 2
  • 11
  • 36
0

You can call model functions form view. Remember: This solution is against MVC pattern

Model:

function getdata() {
  $query = $this->db->query($sql);
  return $query->result_array();
}

View:

foreach($this->modelname->getdata() as $item) {

}
Igor S.
  • 3,332
  • 1
  • 25
  • 33