Reputation: 135
this is my controller
<?php
class Site extends CI_Controller{
public function index(){
$this->load->view('home');
}
}
?>
This is my model
<?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;
}
}
}
?>
and this is my view PAge
<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>
So am calling the model in view called home.php page but its showing an error Call to a member function getAllQA() on a non-object in So but when am calling the model in controller its working fine but why is it showing error when am loading and calling the method in view page
Upvotes: 4
Views: 1671
Reputation: 9044
Load your models inside the constructor of your 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);
}
}
?>
Upvotes: 2
Reputation: 41
not sure if you've done it. Usually you call your model from within the controller. In your case it would be:
class Site extends CI_Controller{
public function index(){
// load your model
$this->load->model('adminmodel');
// do your fancy stuff
$data['allQA'] = $this->adminmodel->getAllQA();
// here you can pass additional data e.g.
$data['userdata'] = $this->adminmodel>getuserinfo();
// pass data from controller --> view
$this->load->view('home',$data);
}
}
You can access the data in your view file by acessing $allQA or $userdata respectively. E.g.
foreach ($allQA as $qa){
echo $qa->question . "<br>" . $qa->option . "<br>";
}
or somewhere within a div
<div class="userbadge">
<?php echo $userdata; ?>
</div>
Upvotes: 0
Reputation: 650
You should not be loading Models from view files. Codeigniter is a MVC framework which means that all communication with the model should be handled by the controller.
The technical reason that this isn't working is likely that the view file is not a php class and therefore $this does not exist. Thats regardless, if you want to do something like this, don't use codeigniter!
Upvotes: 1