Search code examples
codeignitermysql-num-rows

num_rows return ZERO all the time in CodeIgniter


I have a simple code in CI Model for Login BUT it always return 0.

     $this->db->select('*');
     $this->db->from('cms_users');
     $this->db->where('username', "admin");
     $this->db->where('password', "admin01");
     $query = $this->db->get();
     echo $query->num_rows();exit;

It always print 0.

When i try echo $this->db->get_compiled_select();exit; and run in phpmyadmin it return one value.


Solution

  • I would think because you are echoing instead of return

    And you have exit on there as well I would not use exit;.

    Model: User_model.php

    <?php
    
    class User_model extends CI_Model {
    
        public function count() {
           $this->db->where('username', "admin");
           $this->db->where('password', "admin01");
           $query = $this->db->get($this->db->dbprefix . 'cms_users');
           return $query->num_rows();
        }
    
    }
    

    Controller: Weclome.php

    <?php
    
    class Welcome extends CI_Controller {
    
       public function __construct() {
          parent::__construct();
          $this->load->model('user_model');
       }
    
       public function index() {
          $data['user_total'] = $this->user_model->count();
    
          $this->load->view('welcome_message', $data);
       }
    
    }