How to query a database from a view - CodeIgniter

I have a request that runs in the controller:

$data['query'] = $this->Member->select_sql($id); $this->load->view('myform'); 

and then displays the data in the form:

 foreach ($query->result() as $row): echo $row->post_title; echo $row->post_user_id; endforeach; 

So this gives me a list of posts made by the user. Now I would like to run another query, which will be for each record cycle through my user table and display user information next to each message. (I do not want to select data from the view or combine these 2 tables at this time in MySQL)

Any ideas?

+4
source share
2 answers

Insert the database adapter or the corresponding table object into the view.

From your code above, I would suggest that it would be

 $data['userModel'] = $this->User; 

Then use it from there to run your request, for example.

 $user = $userModel->select_sql($row->post_user_id); 
+5
source

Although this is not a good practice, the β€œcleanest” approach will be as follows:

  • Take an instance of CI in a view
  • Download the model containing the required data retrieval request functions.
  • Execute function from model in view

So in the view:

 $CI =& get_instance(); $CI->load->model('modelname'); $result = $CI->modelname->functionname(); var_dump($result); 

Tested and working.

+6
source

All Articles