4

I am trying to display my db query result in my controller, but I don't know how to do it. could you please show me?

Controller

 function get_name($id){

 $this->load->model('mod_names');
 $data['records']=$this->mod_names->profile($id);

// I want to display the the query result here 
 // like this:  echo $row ['full_name'];

 }

My Model

function profile($id)
    {  

        $this->db->select('*');
        $this->db->from('names');
        $this->db->where('id', $id); 
        $query = $this->db->get();


        if ($query->num_rows() > 0)
        { return $query->row_array();
        }
        else {return NULL;}

    }   

3 Answers 3

6
echo '<pre>';
print_r($data['records']);

or

 echo $data['records'][0]['fullname'];
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply. I have tried echo $data['records'][0]['fullname']; But I get this message: Undefined offset: 0 Thanks :)
ok change it like this it will work fine echo $data['records']['fullname'];
4

Model:

function profile($id){  
    return $this->db->
    select('*')->
    from('names')->
    where('id', $id)->
    get()->row_array();
} 

Controller:

function get_name($id){

    $this->load->model('mod_names');
    $data['records']=$this->mod_names->profile($id);

    print_r($data['records']); //All 
    echo $data['records']['full_name']; // Field name full_name

}

Comments

3

You do that inside a View, like this.

Controller:

 function get_name($id){

    $this->load->model('mod_names');
    $data['records']=$this->mod_names->profile($id);
    $this->load->view('mod_names_view', $data); // load the view with the $data variable

 }

View (mod_names_view):

 <?php foreach($records->result() as $record): ?>
     <?php echo $record->full_name); ?>
 <?php endforeach; ?>

I would modify your model then to something like this (it worked for me):

function profile($id)
{  
    $this->db->select('*');
    $this->db->from('names');
    $this->db->where('id', $id); 
    $query = $this->db->get();

    if ($query->num_rows() > 0)
    {
     return $query; // just return $query
    }
}

1 Comment

Yes I know how to do it in the view file. But I need to get the query result in my controller. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.