CodeIgniter Forums
Newbie Question: DB in Model - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: Newbie Question: DB in Model (/showthread.php?tid=31219)



Newbie Question: DB in Model - El Forum - 06-10-2010

[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.


Newbie Question: DB in Model - El Forum - 06-10-2010

[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.


Newbie Question: DB in Model - El Forum - 06-10-2010

[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.


Newbie Question: DB in Model - El Forum - 06-10-2010

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


Newbie Question: DB in Model - El Forum - 06-12-2010

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

InsiteFX


Newbie Question: DB in Model - El Forum - 06-12-2010

[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();
   }
}