Welcome Guest, Not a member yet? Register   Sign In
Beginner : retrieving data in View from Controller
#1

[eluser]djsuperfive[/eluser]
Hi,
I have a stupid question:
My controller calls a Model method to retrieve data from MySQL. I want to pass it to my view. But when i want to display the view in the browser, the $data in unknown and i get an error:
Code:
// following lines are in my controller
// and the var_dump is OK.
$data = $this->mUsers->getAll();
var_dump($data);
$this->load->view('vUsers', $data);

Code:
// following line are in my view
// and the var_dump generates an error.
<html>
  <head>
    <title>Les articles</title>
  </head>
  <body>
    <h1>Les articles du site</h1>
    &lt;?
    var_dump($data);
    ?&gt;
  &lt;/body&gt;
&lt;/html&gt;

And the error message in the browser :
Code:
A PHP Error was encountered

Severity: Notice

Message: Undefined variable: data

Filename: views/vUsers.php

Line Number: 8
#2

[eluser]Twisted1919[/eluser]
Try with
Code:
$data = array();
$data['from_db'] = $this->mUsers->getAll();
var_dump($data);
$this->load->view('vUsers', $data);

Code:
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Les articles&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    <h1>Les articles du site</h1>
    &lt;?
    var_dump($data['from_db']);
    ?&gt;
  &lt;/body&gt;
&lt;/html&gt;

Also your model function should return $query->result(); or $query->result_array();
#3

[eluser]djsuperfive[/eluser]
Thank you for your quick response.

Indeed, it works when i pass an array to the view, not an object. My Model return $query->result.
There's no way to pass an object to the view ?
#4

[eluser]Twisted1919[/eluser]
You can assign that object as an array key of "$data" array .
At least this is the method i know it works , and as you can see , assigning the object directly to $data will not work .
Just do it in CI way , and assign that object to an array key, this is the right way Smile
#5

[eluser]djsuperfive[/eluser]
ok i get it. Thanks !
#6

[eluser]Aken[/eluser]
When calling your information inside the view, you don't need to call the $data array either. The key ('from_db' in this case) will be turned into a variable of its own when in the view.

Controller:
Code:
$data = array();
$data['from_db'] = $this->mUsers->getAll();

$this->load->view('vUsers', $data);

View:
Code:
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Les articles&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    <h1>Les articles du site</h1>
    &lt;?
    var_dump($from_db);
    ?&gt;
  &lt;/body&gt;
&lt;/html&gt;
#7

[eluser]djsuperfive[/eluser]
yep thank you !




Theme © iAndrew 2016 - Forum software by © MyBB