2013-07-31 34 views
0

我的模型:笨如何显示功能的数据

function get_data($id) 
{ 
    $this->db->select('id, Company, JobTitle');  
    $this->db->from('client_list');  
    $this->db->where('id', $id); 
    $query = $this->db->get();    

    return $query->result(); 
} 

我想从get_data()得到的数据,这是正确的做法?

public function show_data($id) 
{ 
    $data = $this->get_data($id); 
    echo '<tr>';  
    echo '<td>'.$data['Company'].'</td>';        
    echo '<td>'.$data['JobTitle'].'</td>'; 
    echo '<td>'.$data['id'].'</td>'; 
    echo '<td></td>';   
    echo '</tr>';           
} 

回答

0

您可以使用foreach循环打印

foreach ($data->result() as $row) 
{ 
    echo '<tr>';  
    echo '<td>'.$row['Company'].'</td>';        
    echo '<td>'.$row['JobTitle'].'</td>'; 
    echo '<td>'.$row['id'].'</td>'; 
    echo '<td></td>';   
    echo '</tr>'; 
} 

谢谢

0

只是为了提高答案,我用"general_model"我所有的控制器,也有一些我需要特殊查询的例外,我只是创建所需的模型,所以“general_model”保持不变,我可以使用它在任何项目中。

例如

general_model.php控制器

function _getWhere($table = 'table', $select = 'id, name', $where = array()) { 

    $this->db->select($select); 
    $q = $this->db->get_where('`'.$table.'`', $where); 

    return ($q->num_rows() > 0) ? $q->result() : FALSE; 
} 
. 
. 
. 
//bunch of another functions 

只需要调用

$this->data['books'] = $this->general_model->_getWhere('book', '*', array('active' => '1')); 
$this->render('book_list_view'); // $this->load->view('book_list_view', $this->data); 

旁注:我延伸是CI_Controller因此,我使用$this->data['books']代替$data['books']将数据传递到视图

视图

//check if there are any data 
if ($books === FALSE) { 
    //some error that there are no books yet 
} else { 
    //load data to table or something 
    foreach ($books as $book) { 
     $book->id; // book id 
    } 
}