1
votes

I'm using the CI framework and I'm trying to make a foreach loop so that all products of my site are displayed.

This is my controller file:

class AlleCadeausController extends CI_Controller {

public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus');   
}

This is my model file:

<?php 
class Allecadeaus_model extends CI_Model {
   public function __construct()
   {
       parent::__construct();
   }
    public function get_cadeaus()
    {
        $query = $this->db->query('SELECT * FROM products');     
        $result = $query->result_array();    
        return $result;
    }
}

this is my view:

<?php
foreach ($cadeaus as $cadeau)
{
    echo $cadeau->product_naam;
}
?>

The error is:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: cadeaus

Filename: views/allecadeaus.php

Line Number: 3

Backtrace:

File: /home/ubuntu/workspace/application/views/allecadeaus.php Line: 3 Function: _error_handler

File: /home/ubuntu/workspace/application/controllers/AlleCadeausController.php Line: 11 Function: view

File: /home/ubuntu/workspace/index.php Line: 315 Function: require_once

My table name is products

6

6 Answers

6
votes

You havn't passed the $data variable in your controller. Please follow below code:

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

So, your controller function should be like below.

public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus', $data);


}

Cheers, you are done.

1
votes
public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus',$data);


}

try this in you controller

1
votes

You haven't pass data to the view you just load view. for passing data to view you have to do

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

Here are good documentation for passing data from controller to view Contact ME

1
votes

You should pass the data to the view follow the below code:

public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus, $data');
}
0
votes

You have to pass $data with the view.

$this->load->view('allecadeaus',$data);
0
votes

You need pass array of data in second argument. Please use this :

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

If you load child view in allecadeaus, then you don't need to pass array of data. You can directly access all variables from array of data.