我是codeigniter的新手我在模型中有一个简单的查询,如下所示:
function showbook(){
$number_test =10;
$this->db->select('qid, question, q_type');
$this->db->from('qbank');
$this->db->where('q_type',2);
$this->db->limit($number_test);
$query = $this->db-> get();
return ($query->result());
}
所以在我的控制器中我想将查询结果存储到变量中并发送到查看并在其中使用它,这是我的控制器:
public function show(){
$this->load->model('add_book_model');
$data['stuff'] = $this->add_book_model->showbook();
foreach ($data as $row)
{
$question[] = $row->question;
// echo $row->question;
}
$this->load->view('desktop/view_book',$question);
}
最后,这是我想要回应结果的观点的一部分。我想知道在模型中处理数据是正确的,将它们保存在控制器中的变量中并将它们发送到视图我的意思是它是代码点燃时MVC的真正含义吗?如果是的话,我的错误是什么?
<?php
print_r ($question[]);
?>
答案 0 :(得分:1)
在您的模型中使用return result_array
而不是result
function showbook(){
$number_test =10;
$this->db->select('qid, question, q_type');
$this->db->from('qbank');
$this->db->where('q_type',2);
$this->db->limit($number_test);
$query = $this->db-> get();
return ($query->result_array());
}
在您的控制器中
$this->load->model('add_book_model');
$data['stuff'] = $this->add_book_model->showbook();
$this->load->view('desktop/view_book',$data);
}
最后在视图中:
<?php
if(!empty($stuff)) {
foreach ($stuff as $single_stuff) {
print_r ( $single_stuff['question'] );
}
}
?>
答案 1 :(得分:1)
In model try this
function showbook(){
$number_test =10;
$this->db->select('qid, question, q_type');
$this->db->from('qbank');
$this->db->where('q_type',2);
$this->db->limit($number_test);
$query = $this->db-> get();
return $query->result();
}
In controller
$this->load->model('add_book_model');
$data['result'] = $this->add_book_model->showbook();
$this->load->view('desktop/view_book',$data);
}
Now in view you can access result array using foreach loop
foreach($result as $row){
echo $row->qid;
echo $row->question;
echo $row->q_type;
}
If you are echoing value in html try like this
<table>
<th>qid</th>
<th>question</th>
<th>question type</th>
foreach($result as $row){
<td><?php echo $row->qid; ?></td>
<td><?php echo $row->question; ?></td>
<td><?php echo $row->q-type; ?></td>
}
</table>
答案 2 :(得分:0)
试试这个 在控制器
public function show(){
$this->load->model('add_book_model');
$data['stuff'] = $this->add_book_model->showbook();
$this->load->view('desktop/view_book',$data);
}
并在您的视图中
foreach($stuff as $value){
echo $value->question;
}