Reputation: 393
In post Codeigniter result_array() returning one row https://stackoverflow.com/users/315828/xbonez answer was like this
function getAllUsers()
{
$rows = array(); //will hold all results
$query = $this->db->get('users');
foreach($query->result_array() as $row)
{
$rows[] = $row; //add the fetched result to the result array;
}
return $rows; // returning rows, not row
}
In your controller:
$data['users'] = $this->yourModel->getAllUsers();
$this->load->view('yourView',$data);
In your view
//in your view, $users is an array. Iterate over it
<?php foreach($users as $user) : ?>
<p> Your first name is <?= $user['fName'] ?> </p>
<?php endforeach; ?>
initiating query from controller and the query result is in $data['users']
, but in view we are iterating in as $users
. why this is?
Upvotes: 3
Views: 84
Reputation: 986
Just check loader.php
in system/core
and find "public function view"
, it will answer your question.
Upvotes: 1
Reputation: 4584
If you set in your controller ,
$data['users'] = $this->yourModel->getAllUsers();
$this->load->view('users',$data); //first argument will be passed to view as $users
In your view , you will call about parameter
<?php foreach($users as $user) : ?>
<p> Your first name is <?= $user['fName'] ?> </p>
<?php endforeach; ?>
Upvotes: 1
Reputation: 22532
$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
Upvotes: 2
Reputation: 11693
In codeigniter(or mvc framework such as cakePHP), we build array with key and value in Controller. And then pass it to view as variables.
So $data['users']=array(key=>val)
will goto view and accessed as echo $users['key']
.
See carefully All variable keys in controller(such as $data['users']
here users is key) become Actual variables in view(such as $users
), which is why we call it MVC structure.
Upvotes: 1