Search code examples
phpmysqlcodeigniter-2

SQL count Not sure How to get it to work with model, view and controller


I am not sure on how to do this with the model, view, and controller. I currently have it in the view only. I know this is bad practice that is why I am trying to see if I can get help. I have google how to create count but I cannot find any tutorials on this. Any help would be appreciated also this code is working.

view page

 ?php $this->db->where('status','Happy');
    $this->db->from('data');
    $count = $this->db->count_all_results();?>

    <a href='http://google.com'><?php echo 'Happy =' . $count;
    ?></a><br>

Solution

  • Model

    <!-- model.php -->
    <?php
      
      class Model extends CI_Model{
        
        public fucntion __construct(){
        
          $this->load->database();
        }
    
        public function count(){
          
          
          $this->db->select(*);
          $this->db->from('data');
          $this->db->where('status','Happy');
          $count = $this->db->count_all_results();
          
          return $count;
          
        }
    
      }
    ?>

    Controller

    <!-- controller.php -->
    
    <?php
        
      class Controller extends CI_controller{
    
        public function __construct(){
          
          parent::__construct();
        }
    
        public function index(){
      
          $this->load->model('model');
          $data['result'] = $this->Model->count();
          $this->load->view('printresult',$data);
        
        }
    
      }
    
    
    
    
    ?>

    View