Codeigniter : displaying query result in controller

杀马特。学长 韩版系。学妹 提交于 2019-12-05 02:06:13

问题


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;}

    }   

回答1:


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

or

 echo $data['records'][0]['fullname'];



回答2:


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

}



回答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
    }
}


来源:https://stackoverflow.com/questions/10684329/codeigniter-displaying-query-result-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!