Welcome Guest, Not a member yet? Register   Sign In
how to send loop data to view
#1

[eluser]jcjc[/eluser]
Querying a database to return data in a loop to a view. How can I send the data to the view?

my function inside a model code is:

Code:
$query = $this->db->get('item');

  if($query->num_rows() > 0 )
  {

   foreach($query->result() as $row)
   {
    
      $data[] = $row;
   }

    return $data;
  }

I thought I could just use this to send it to the view:

Code:
$this->data['itemName'] = $data['ItemName'];

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

error message I get is:

Code:
Undefined variable: data

if $data is being returned howcome data is undefined??

Thanks
#2

[eluser]Tpojka[/eluser]
Have you set
Code:
public $data = array();
at the beginning of the class?
#3

[eluser]jcjc[/eluser]
I did try that but the error persists.
#4

[eluser]Tpojka[/eluser]
You don't need $data variable in your view file, but output $itemName there:
Code:
var_dump($itemName);exit;

If not helping, instead these lines:
[quote author="jcjc" date="1399560525"]
Code:
$this->data['itemName'] = $data['ItemName'];

$this->load->view('items', $this->data);
[/quote]
output what you have got from model:
Code:
var_dump($this->model_name->model_method());exit; // this should be object or array of model data
Have you made relations between controller and model?
It is not seen in provided code.
#5

[eluser]jcjc[/eluser]
When I try var_dump($itemName);exit; I get NULL.

When I try var_dump($this->model_name->model_method());exit; I get the results in the array. So the model works and returns the data to the controller - How can I pass this to the view?
#6

[eluser]Tpojka[/eluser]
You solved it than, almost.
Code:
$this->data = $this->model_name->model_method();
$this->load->view('items', $this->data);
Than you approach by keys of associative array you've already got (I.e. $nameItem if 'nameItem' is key of value in array).
#7

[eluser]jcjc[/eluser]
Ok - that work - how do I go about the last part associative array to a view??
#8

[eluser]Tpojka[/eluser]
Sorry, I don't understand well.
Can you write out here what array looks like and also what are you intending to use from it?
#9

[eluser]jcjc[/eluser]
In my view I currently have:

Code:
<?php foreach ($product as $item){ ?>

              <?php var_dump($item); ?>

              <?php echo $item['ProductName']; ?>

              <?php } ?>

I get the following error:

Fatal error: Cannot use object of type stdClass as array
#10

[eluser]jcjc[/eluser]
found the issue Smile

should have been:

Code:
<?php echo $item->ProductName; ?>

Thanks for your help Smile




Theme © iAndrew 2016 - Forum software by © MyBB