Reputation: 156
I'm trying to count the number of rows of my table that meet specific criteria. My code works fine and returns the number of rows accordingly. But i'm having problem to echo that number of rows in my view
my controller:
function index(){
$data['states'] = $this->state_model->get_cities();
$data['status'] = $this->state_model->get_status();
$this->load->view('testviewad', $data);
}
in 2nd the line the number of rows are stored. if i do
<?php echo $status?>
in my view it shows
0
0
0
0
But i should show
0
1
3
0
if i echo from the model the counted number of the rows shows correctly. So my query is working. But i think i'm making mistake while passing to the view. Can any one tell me what i'm doing wrong.
my model:
function get_status(){
$states = $this->db->get('state');
$like = array();
foreach ($states->result() as $state){
$cities = $this->db->get_where('city', array('state_id'=> $state->id));
foreach ($cities->result() as $v){
$s=$v->city_id."<br/>";
$this->db->where('city_city_id',$v->city_id);
$this->db->where('status_status_id',1);
$q=$this->db->get('info');
$sql = $q->num_rows();
}
return $sql;
}
}
I'm using codeigniter. Thanks in advance.
Upvotes: 0
Views: 473
Reputation: 13630
My guess is that $data['status']
is getting overwritten each iteration, leaving the value of 0
when it's passed to the view.
It's tough to tell exactly without seeing the relevant code "in context", but you could do this:
$data['states'] = $this->state_model->get_cities();
$data['status'][] = $this->state_model->get_status(); // adding brackets - now $status will be an array
Then you could loop through $status
in the view:
foreach ($status as $s)
{
echo $s . "\n";
}
UPDATE
After reviewing more code. It seems you're overwriting $sql
in the get_status()
model method. Change that to this:
function get_status(){
$states = $this->db->get('state');
$like = array();
foreach ($states->result() as $state){
$cities = $this->db->get_where('city', array('state_id'=> $state->id));
foreach ($cities->result() as $v){
$s=$v->city_id."<br/>";
$this->db->where('city_city_id',$v->city_id);
$this->db->where('status_status_id',1);
$q=$this->db->get('info');
$sql[] = $q->num_rows(); // add the array brackets
}
}
// move this down outside of the first foreach loop
return $sql; // now $sql is an array of values
}
Then, your call to $data['status'] = $this->state_model->get_status();
returns an array and can be looped through in the view:
foreach ($status as $s)
{
echo $s . "\n";
}
Upvotes: 2