codeigniter - 我的 codeigniter 模型在 Controller 中工作正常,但在 View 页面中调用时显示错误

标签 codeigniter

这是我的 Controller

<?php
class Site extends CI_Controller{
    public function index(){    
    $this->load->view('home');
    }
}
?>

这是我的模型
<?php

class AdminModel extends CI_Model{

//function to get all the questions 

    function getAllQA(){
        $result=$this->db->get('question');
        if($result->num_rows()>0){ //this checks if the result has something if blank means query didn't get anything from the database
        return $result;
        }
        else{
        return false;
        }
    }
}
?>

这是我的观点页面
<form method="get" action="">
        <div id="container">    
            <?php
                $this->load->model('adminmodel');
                if($result=$this->adminmodel->getAllQA()){
                    foreach($result->result() as $rows){
                        echo $rows->question;
                        echo $rows->option1;
                    }
                }
                else{
                    echo "No question found";
                }
            ?>
        </div>
    </form>

所以我在名为 home.php 页面的 View 中调用模型,但它显示错误 中调用非对象上的成员函数 getAllQA()所以但是当我在 Controller 中调用模型时它工作正常但是为什么在 View 页面中加载和调用方法时显示错误

最佳答案

在 Controller 的构造函数中加载模型

your controller should be like this

<?php
  class Site extends CI_Controller{
    function __construct()
    {
        parent::__construct();
        $this->load->model('adminmodel');

    }
    //if you want to pass data or records from database to view do as blow code
    public function index()
    {    
        //define an empty array
        $data = array();
        $records = $this->adminmodel-> getAllQA();

        $data['records'] = $records;

        //pass the data to view you can access your query data inside your view as $records
        $this->load->view('home',$data);
    }
  }
?>

关于codeigniter - 我的 codeigniter 模型在 Controller 中工作正常,但在 View 页面中调用时显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18670226/

相关文章:

php - 消息:未定义的属性:CI_Loader::$cart (Codeigniter 3)

php - 在 php 环境中全局设置日期和时间

javascript - Codeigniter:接受空格和符号以使用 JQuery 进行验证

php - 在 CodeIgniter 中添加新页面

regex - CI 3.0.4 大 where_in 查询导致消息 : preg_match(): Compilation failed: regular expression is too large at offset)

php - 查询结果数组,每一行的列字段为字符串

javascript - Codeigniter:Ajax 发送 id 和名称,但函数仅接收 id

php - 在 CodeIgniter 中使用 DOMpdf 生成 PDF

php - 尝试从 2 个表 codeigniter 获取数据时出错

php - 使用ajax将Null插入数据库