-1

Im super new to codeigniter and am trying to figure out how to use the Models, ive used a MVP framework before but it was a bit different. I have the users controller, which initializes the model(I think I did it right), then the model has a function, that gets a row by email.

The controller looks like:

class Users extends CI_Controller{
    public function login(){
        $this->load->model('users_model');

        $this->users_model->login('slavigne@uark.edu', 'abcdefg');

        $this->load->view('templates/header');
        $this->load->view('users/login');
        $this->load->view('templates/footer');
    }
}

and the model looks like:

class users_model extends CI_Model{
    public function users_model(){
            parent::__construct();
    }

    public function login($email, $password){
        $query = $this->db->get_where('users', array('email' => $email));
        return $query->result();
    }
}

The problem im getting is:

Call to a member function get_where() on a non-object

which I understand means that db isn't an object, but all the code I saw for models, say that this should work. Any help or advice would be great! Also any advice on newbie mistakes to codeigniter would be nice!

tereško
  • 57,247
  • 24
  • 95
  • 149
samuraiseoul
  • 2,740
  • 8
  • 43
  • 64

1 Answers1

2

You seem to miss $this->load->database();

class users_model extends CI_Model{
    public function users_model(){
            parent::__construct();
    }

    public function login($email, $password){
        $this->load->database();
        $query = $this->db->get_where('users', array('email' => $email));
        return $query->result();
    }
}

You can also auto-load the database library in the application/config/autoload.php file.

$autoload['libraries'] = array('database');

If you do so, you don't need to load it manually each time, but it will also mean it loads on pages where no database calls are made. Might be more of a care for optimizers to spare bandwidth.

Also if you are using more than one database connection, you should still use the $this->load->database(); tho. See this link for more info: http://ellislab.com/codeigniter/user-guide/database/connecting.html

$DB1 = $this->load->database('group_one', TRUE);
$DB2 = $this->load->database('group_two', TRUE);

Instead of using..

$this->db->query();
$this->db->result();

..you will instead use:

$DB1->query();
$DB1->result();
$DB2->query();
$DB2->result();

You can still add the load to the __construct(), so you only need one line per controller.