My codeigniter model works fine in the controller, but when called on the browse page showing an error

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 look 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, I call the model called home.php, but it shows an error Calling the getAllQA () member function for the non-object in . So, but when I call the model in the controller it works fine, but why does it show an error when loading and calling the method on the browse page.

+4
source share
3 answers

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); } } ?> 
+2
source

You should not load Models from view files. Codeigniter is an MVC framework that means that all communications with the model must be handled by the controller.

The technical reason this doesn't work is likely that the view file is not a php class, and therefore $ this does not exist. That is independent, if you want to do something similar, then do not use codeigniter!

+1
source

Not sure you did it. Usually you call your model from the controller. In your case, it will 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 eg $data['userdata'] = $this->adminmodel>getuserinfo(); // pass data from controller --> view $this->load->view('home',$data); } } 

You can access the data in the view file by specifying $ allQA or $ userdata respectively. For instance.

 foreach ($allQA as $qa){ echo $qa->question . "<br>" . $qa->option . "<br>"; } 

or somewhere in the div

  <div class="userbadge"> <?php echo $userdata; ?> </div> 
0
source

Source: https://habr.com/ru/post/1501043/


All Articles