user1579200
user1579200

Reputation: 15

How to pass data from the controller layer to the view layer in CodeIgniter?

I have this error in CI:

A PHP Error was encountered Severity: Notice Message: Undefined variable: news Filename: controllers/First.php Line Number: 33

A PHP Error was encountered Severity: Notice Message: Undefined variable: news Filename: views/welcome_view.php Line Number: 1

A PHP Error was encountered Severity: Warning Message: Invalid argument supplied for foreach() Filename: views/welcome_view.php Line Number: 1

My controller:

<?php
if ( ! defined('BASEPATH')) exit ('No direct script access allowed');

class First extends CI_Controller
{
    
    public function __construct()
    {
        parent::__construct();
        $this->load->model('materials_model');
    }

    // ...my constructor
  
    public function mat()
    {
        $this->load->model('materials_model');
        $this->materials_model->get();
        $data['news'] = $this->materials_model->get();
    
        $this->load->view('welcome_view',$news);
    
        if (empty($data['news'])) {
            echo 'Array is Null';
        } else {
            echo 'Array has info';
        }
    }
}

My model:

<?php
if ( ! defined('BASEPATH')) exit ('No direct script access allowed');

class Materials_model extends CI_Model
{
    public function get()
    {
        $query = $this->db->get('materials');
        return $query->result_array();
    }
}

My view :

<?php foreach ($news as $one):?>
    <?=$one['author']?>
<?php endforeach; ?>

I know, that array which I pass into the view IS NOT NULL (I check it for print_r and if, else construction), but I can pass it and view it. What mistake do I have?

Upvotes: 0

Views: 419

Answers (3)

GautamD31
GautamD31

Reputation: 28753

In the Controller you need to pass data not news like

$data['news'] = 'Something';
$this->load->view('welcome_view',$data);

and in your view you can use

foreach($news as $new)
{
   //Go Here
} 

Upvotes: 0

Edward Ruchevits
Edward Ruchevits

Reputation: 6696

Set variable:

$data['news'] = $this->materials_model->get();

Pass it to the view:

$this->load->view('welcome_view', isset($data) ? $data : NULL);

Access it in the view as a result array:

<?php 
    foreach($news as $item)
    {
        echo $item['id']." - ".$item['some_other_column_title']
    } 
?>

As an option, you can change your get() method in model to return object, not array.

public function get()
{
    $query = $this->db->get('materials');
    return $query->result();
}

Then in view you need handle $news as an object, like that:

<?php 
    foreach($news as $item)
    {
        echo $item->id." - ".$item->some_other_column_title
    } 
?>

Upvotes: 0

Alex Wright
Alex Wright

Reputation: 1771

$this->load->view('welcome_view',$news);

$news is never defined. Maybe you mean to use $data?, CI views expect an assoc array to be passed to them.

Upvotes: 0

Related Questions