PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 29, 2022

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

 January 29, 2022     codeigniter, count, php     No comments   

Issue

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.


Solution

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;


Answered By - Vickel
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing