0

I am trying to access all the bands in my table and print them out in a list, but when I run it I get this error:

Severity: Notice

Message: Undefined property: CI_Loader::$model_bands

Filename: views/band_view.php

Line Number: 16

band_view.php:

<h3>List of Bands:</h3>
<?php
$bands = $this->model_bands->getAllBands();

echo $bands;
?>

model_bands.php:

function getAllBands() {
    $query = $this->db->query('SELECT band_name FROM bands');
    return $query->result();    
}

Could someone pleease tell me why it is doing this?

4 Answers 4

2

Why do you need to do this, the correct way is to use the model methods inside a controller, then passing it to the view:

public function controller_name()
{
    $data = array();
    $this->load->model('Model_bands'); // load the model
    $bands = $this->model_bands->getAllBands(); // use the method
    $data['bands'] = $bands; // put it inside a parent array
    $this->load->view('view_name', $data); // load the gathered data into the view
}

And then use $bands (loop) in the view.

<h3>List of Bands:</h3>
<?php foreach($bands as $band): ?>
    <p><?php echo $band->band_name; ?></p><br/>
<?php endforeach; ?>
Sign up to request clarification or add additional context in comments.

1 Comment

Are you sure its foreach($bands as $band)? Because its saying the variable bands doesnt exist
1

Did you load your model in the Controller?

    $this->load->model("model_bands");

Comments

0

You need to change your code like Controller

public function AllBrands() 
{
    $data = array();
    $this->load->model('model_bands'); // load the model
    $bands = $this->model_bands->getAllBands(); // use the method
    $data['bands'] = $bands; // put it inside a parent array
    $this->load->view('band_view', $data); // load the gathered data into the view
}

Then View

<h3>List of Bands:</h3>
<?php foreach($bands as $band){ ?>
    <p><?php echo $band->band_name; ?></p><br/>
<?php } ?>

Your Model is ok

function getAllBands() {
    $query = $this->db->query('SELECT band_name FROM bands');
    return $query->result();    
}

1 Comment

Are you sure its foreach($bands as $band)? Because its saying the variable bands doesnt exist
0

You forgot to load the model on your controller:

//controller

function __construct()
{
    $this->load->model('model_bands'); // load the model
}

BTW, why are you calling the model directly from your view? Should it be:

//model
$bands = $this->model_bands->getAllBands();
$this->load->view('band_view', array('bands' => $bands));

//view
<h3>List of Bands:</h3>
<?php echo $bands;?>

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.