Reputation: 2000
I am new to codeigniter I have a simple query in model like this below :
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());
}
so in my controller I want to store query result into a variable and send to view and use it in that and this is my controller :
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);
}
and finally this is the part of my view that I want to echo results. I want to know that is that correct to process data in model save them in variable in controller and send them to view I mean is it the true meaning of MVC in code ignite? If yes what is my mistake?
<?php
print_r ($question[]);
?>
Upvotes: 1
Views: 2403
Reputation: 1045
try this in controller
public function show(){
$this->load->model('add_book_model');
$data['stuff'] = $this->add_book_model->showbook();
$this->load->view('desktop/view_book',$data);
}
and in your view
foreach($stuff as $value){
echo $value->question;
}
Upvotes: 0
Reputation: 219
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>
Upvotes: 2
Reputation: 6928
In your model use return result_array
instead of 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());
}
In your controller
$this->load->model('add_book_model');
$data['stuff'] = $this->add_book_model->showbook();
$this->load->view('desktop/view_book',$data);
}
Finally in the view:
<?php
if(!empty($stuff)) {
foreach ($stuff as $single_stuff) {
print_r ( $single_stuff['question'] );
}
}
?>
Upvotes: 1