这是我的 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/