2014-09-26 89 views
0

我试图访问所有的乐队在我的表并打印出来的清单,但是当我运行它,我得到这个错误:笨 - 未定义的属性错误

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();  
} 

有人能pleease告诉我它为什么这样做呢?

回答

2

为什么你需要做到这一点,正确的方法是使用一个控制器内部模型方法,然后将它传递给视图:

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 
} 

然后用$bands视图(循环)。

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

你确定它的foreach($ band为$ band)吗?因为它说变量带不存在 – Divergent 2014-09-26 16:36:25

1

您是否在Controller中加载模型?

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

您需要更改像 控制器

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 
} 

代码然后查看

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

模型是确定

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

你确定它的foreach($ band为$ band)吗?因为它说变量带不存在 – Divergent 2014-09-26 16:35:27

0

你忘了在加载模型ÿ我们的控制器:

//controller 

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

顺便说一句,你为什么直接从你的视图调用模型?它应该是:

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

//view 
<h3>List of Bands:</h3> 
<?php echo $bands;?> 
相关问题