我正在尝试访问表格中的所有乐队并将其打印在列表中,但是当我运行它时,我收到此错误:
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();
}
有人可以告诉我为什么会这样做吗?
答案 0 :(得分: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; ?>
答案 1 :(得分:1)
您是否在控制器中加载了模型?
$this->load->model("model_bands");
答案 2 :(得分: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();
}
答案 3 :(得分: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;?>