Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter Undefined property: xxxx_model::$db only from Model

First the Model class:

    class Xxxx_model extends Model
    {
      function XxxxModel()
      {
        parent::Model();
        $this->load->database();
      }

      function isInDatabase()
      {
        // Please ignore the sql query, it's just to show some random sql code with results
11.      $result = $this->db->query('SELECT * FROM someTable WHERE ...');
        $numberOfRows = $result->num_rows();
        ... 
        return $test;
      }
    }

Now the controller:

function someLogic()
{
  $this->load->model('xxxx_Model', 'xxxxModel'); // not necessary to specify
  $this->xxxxModel->isInDatabase();
}

When I run this I get the error:

Severity: Notice  --> Undefined property: Xxxx_model::$db .../xxxx_model.php line 11

I have no idea why this is. If I put the db code in the controller it seems to work, it's only with this setup in the model that it fails. I can't for the life of me figure out where the code is astray...

like image 737
Stephane Grenier Avatar asked Jun 20 '11 18:06

Stephane Grenier


3 Answers

You have to load the db library first. In autoload.php add below code,

$autoload[‘libraries’] = array(‘database’);
like image 68
uwublogs Avatar answered Nov 15 '22 12:11

uwublogs


add library 'datatabase' to autoload.

/application/config/autoload.php

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

Propably you're started new project, like me ;-)

like image 22
Tonci14 Avatar answered Nov 15 '22 11:11

Tonci14


To add to atno's answer:

class Xxxx_model extends Model
{
  function XxxxModel() //<--- does not match model name Xxxx_model
  {
    parent::Model();
    $this->load->database();
  }

Basically, you are not constructing the class or the parent class Model. If you are on PHP5, you may use __construct(), otherwise you must match the class name exactly, regardless of what alias you load it with in your controller. Example:

class Xxxx_model extends Model
{
  function __construct()
  {
    parent::__construct(); // construct the Model class
  }
}

I may be mistaken (haven't used 1.x in a while), but if you construct the Model class, there's no need to load the database if you are using the default connection settings in config/database.php, it should already be loaded for you.

like image 39
Wesley Murch Avatar answered Nov 15 '22 11:11

Wesley Murch