Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't CI convert count statement to an array?

I'm trying to make it so that you can view the number of rows of something on my website, I converted the result into an array and then foreached it in the view, yet it calls the argument invalid.

As I said, I've tried the usual, passing on the data from the model to the controller and then to the view. I tried returning $query->num_rows(); as well as a count_all_results back to the controller array for it to be used in the view, both are invalid.

controller.php

  $this->load->model('Main');
  $data = array(
    'getapps' => $this->Main->countapps()
  );
  $this->load->view('header', $data);

view.php

<?php foreach($getapps as $apps) {
?>

<a href="http://localhost/Dir/index.php/Controller/Apps" class="a-m" id="a-m-id">apps <strong><?php echo $apps; ?></strong></a>

<?php }
?>

model.php

public function countapps() {

$this->db->where('usedby', $_SESSION['uid']);
$this->db->get_where('apps', 'appstatus', 'Used');
$stmt = $this->db->count_all_results();

  return $stmt;
}

What I expect to happen is for the view to display the number of rows, instead it tells me that the foreach argument is invalidly supplied.

like image 660
frogman578 Avatar asked Sep 16 '26 22:09

frogman578


1 Answers

In CI $this->db->count_all_results() substitutes $this->db->get() in a database query. Therefore you cannot use $this->db->get_where() and $this->db->count_all_results() at the same time, use num_rows() instead.

write your model function like this:

public function countapps() {

 $query=$this->db->where('usedby', $_SESSION['uid'])
                 ->get_where('apps', 'appstatus', 'Used');
  $stmt = $query->num_rows();

  return $stmt;
}

you could change in your controller to a shorter:

$data['getapps'] => $this->Main->countapps();

Then in your view, you don't need to use foreach() as $data['getapps'] is not an array but a number. You can output it in the view simply like

echo $getapps;
like image 54
Vickel Avatar answered Sep 18 '26 13:09

Vickel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!