Welcome Guest, Not a member yet? Register   Sign In
Newbie Question: DB in Model
#1

[eluser]Unknown[/eluser]
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() {
parent::Model();
}

public function Test() {
var_dump($this->db);
}
}

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.
#2

[eluser]Ivar89[/eluser]
I assume you connected and all.
something to get you going.
Code:
$data = $this->db->select('*')->get('table_name');
if($data->num_rows() > 0)
{
return $data->result_array();
}
else
{
return false
}
this also checks if the database is empty.
#3

[eluser]Unknown[/eluser]
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.
#4

[eluser]Ivar89[/eluser]
Can I see your controller?
You also have to load your model in the controller.
#5

[eluser]InsiteFX[/eluser]
Try loading the database in your model.

InsiteFX
#6

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

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

//Otherwise
class MyModel extends Model{

   function MyModel(){
      parent::Model();
      $this->load->database();
   }
}




Theme © iAndrew 2016 - Forum software by © MyBB