Reputation: 369
I'm trying to select rows from my DB table based on information I get from the other rows(previous query). The trouble I'm having is converting the $query->result_array();
in the controller to use it in the model again and subsequently the view.
I've tried to do a foreach
loop and returning the $query->result_array();
from the model, this turned out to be problematic as it didn't fit the different stages I have on my website(I have several stages of content).
controller.php
public function firststage() {
$this->load->model('Model');
$get_stage = $_GET["stg"];
$get_results = $this->Model->get_stage_id($get_stage);
foreach ($get_results as $results) {
$id = $results["id"];
}
$data['result'] = $this->Model->stage_results($get_stage, $id);
$this->load->view('stage_view', $data);
}
model.php
public function get_stage_id($get_stage) {
$this->db->where('stage_parent', $get_stage);
$query = $this->db->get('stages');
return $query->result_array();
}
public function stage_results($get_stage, $id) {
$this->db->where('stage_id', $get_stage);
$this->db->where('stage_id', $id);
$query = $this->db->get('stage_contents');
foreach ($query->result_array() as $row) {
$rows[] = array(
'id' => $row["id"],
'name' => $row["name"]
);
}
return $rows;
}
Expected the output selection to be based on the first query result, instead I get the Undefined variable: rows
when I run all of it. I don't think my view is relevant to this question, but please let me know if you think otherwise!
Upvotes: 0
Views: 59
Reputation: 7997
you get the error
Undefined variable: $rows
because your query doesn't return any result, therefore $rows is not defined
you can resolve this checking if there are rows returned:
if($query->num_rows()){
foreach ($query->result_array() as $row) {
$rows[] = array(
'id' => $row["ID"],
'name' => $row["name"]
);
}
}else {$rows='no records found';}
print_r($rows);die;
this prints either the array (if there are results), or 'no records'
or simply do:
$rows = array();
foreach ($query->result_array() as $row) {
$rows[] = array(
'id' => $row["ID"],
'name' => $row["name"]
);
}
then you get an empty array if there are no results
Upvotes: 2