3

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?

1
  • Because you are passing 'users' as key to your 'data' array in your load view function. Commented Aug 18, 2015 at 6:44

4 Answers 4

2

$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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks.Understood.Thinking,,, this conversion is done by the framework, Not a feature of language. Right?
1

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.

Comments

1

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; ?>

Comments

1

Just check loader.php in system/core and find "public function view", it will answer your question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.