How to query a database from view - CodeIgniter


I have query that runs in the controller:

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

and then outputs data in the view:

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

So this outputs me a list of posts made by a user. Now I would like to run one more query that would for each post loop through my user table and output user information next to each post. (I dont want to select data from a view or joint those 2 tables at this time in MySQL)

Any ideas?

1/15/2010 11:11:48 PM

Accepted Answer

Inject the database adapter or appropriate table object into the View.

From your code above, I'd assume this would be

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

Then use it from there to run your query, e.g.

$user = $userModel->select_sql($row->post_user_id);
1/15/2010 11:30:56 PM

Although it is not a good practice, the "cleanest" approach would be as follows:

  • Grab the CI instance in the View
  • Load the model containing your desired data extraction query functions
  • Run the function from the model in the view

So, in the view:

$CI =& get_instance();
$result = $CI->modelname->functionname();

Tested and working.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow