【问题标题】:CodeIgniter - Undefined Property ErrorCodeIgniter - 未定义的属性错误
【发布时间】:2014-11-20 23:38:51
【问题描述】:

我正在尝试访问我表中的所有波段并将它们打印在一个列表中,但是当我运行它时,我得到了这个错误:

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

有人能告诉我为什么会这样吗?

【问题讨论】:

    标签: php codeigniter properties undefined


    【解决方案1】:

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

    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; ?>
    

    【讨论】:

    • 你确定它的 foreach($bands as $band) 吗?因为它说变量带不存在
    【解决方案2】:

    您是否在 Controller 中加载了模型?

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

    【讨论】:

      【解决方案3】:

      您需要更改您的代码,例如 控制器

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

      【讨论】:

      • 你确定它的 foreach($bands as $band) 吗?因为它说变量带不存在
      【解决方案4】:

      您忘记在控制器上加载模型:

      //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;?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-27
        • 1970-01-01
        相关资源
        最近更新 更多