Newbie Question: DB in Model

Is there a way of accessing the database from a model? Do I have to load something first? Here's a quick example:

class MyModel extends Model {

public function MyModel() {

public function Test() {

When I call the Test function, var_dump shows the db object as NULL. I must be doing something wrong. Any help is greatly appreciated. Thanks.

I assume you connected and all.
something to get you going.
$data = $this->db->select('*')->get('table_name');
if($data->num_rows() > 0)
return $data->result_array();
return false
this also checks if the database is empty.

Thanks for the feedback. Unfortunately, in the model, I can't even get as far as $this->db->select('*')->get('table_name'). Because $this->db is NULL, calling $this->db->select ... triggers a "Fatal error: Call to a member function select() on a non-object ..." error. Its as if $this->db isn't properly loaded and PHP doesn't know that its the database class/library or which ever it is. Any further suggestion?

Edit: Yes, I am connected and have no issue using $this->db in my controllers. Just something about trying to use it in a Model that gives me error.

Can I see your controller?
You also have to load your model in the controller.

Try loading the database in your model.


[quote author="InsiteFX" date="1276362773"]Try loading the database in your model.

Or just autoload the database in config/autoload.php.
$autoload['libraries'] = array('database');

class MyModel extends Model{

   function MyModel(){

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.