Question

I am getting data from a table and showing in my view (codeigniter). In the view I have user id which is of course an integer. I need to get username from user id. How i will get the username from id ?

Model code is below .

class Resumemodel extends CI_Model
{
   function getallresume()
  {
     $query = $this->db->get('resume');
        return $query;
  }
}

Controller code is below.

class Resumec extends CI_Controller 
{
  function resumelist()
  {
    $this->load->model('Resumemodel');
    $query = $this->Resumemodel->getallresume();
    $dt['main_content'] = 'admin/resumeinfo';   
    $dt['query'] = $query;
    $this->load->view('admin/includes/template.php',$dt);
  }
 }

view is below (only required part i put here)

foreach ($query->result() as $row)
{
   $id = $row->user_id;
   // other table data.
 }

So from user id how i will get user name without join Query ?

PS Please provide answer without join query. It will work with join query, but I am looking for alternatives.

I tried with this-

 $objResume = new resumec();  //resumec is the controller
 $username = $objResume->get_username($id); // get_username is function to get username.
 echo $username;

This is working but this is not proper / good way according to MVC logic. So is there any alternatives ?

edit - 2 tables are there. 'user' and 'resume'. user_id is in 'resume' table and uid, username is in 'user' table.

Was it helpful?

Solution

Read about Codeigniter helpers

Simply just extend the helper to include the function that get username by id.

To gain more knowledge, just visit Codeigniter helper

Good Luck

OTHER TIPS

You can do this changes:

class Resumec extends CI_Controller 
{
  function resumelist()
  {
    $this->load->model('Resumemodel');
    $query = $this->Resumemodel->getallresume();
    $usernames = array();
    foreach ($query->result() as $row)
    {
      $usernames[$row->user_id] = $this->get_username($row->user_id);
    }
    $dt['main_content'] = 'admin/resumeinfo';
    $dt['query'] = $query;
    $dt['usernames'] = $usernames;
    $this->load->view('admin/includes/template.php',$dt);
  }
 }

So, into the view you just do this:

foreach ($query->result() as $row)
{
   $id = $row->user_id;
   $username = $usernames[$row->user_id];
}

Like Resumemodel you may/should have Usermodel where you can define function get_user_name($user_id). You can load this model along with Resumemodel and can use get_user_name function wherever you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top