2014-09-26 66 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;?>