开发者

codeigniter model error: Undefined property [duplicate]

开发者 https://www.devze.com 2023-01-10 16:00 出处:网络
This question already has an answer here: Closed 10 years ago. Possible Duplicate: Error : get property of non-object
This question already has an answer here: Closed 10 years ago.

Possible Duplicate:

Error : get property of non-object

I am new to codeigniter model, i try to follow steps in docs to load all user registered in my db.

This is my model: user.php

class User extends Model {
     function user() {
         parent::Model();
     }
     function alluser() {
         $query = $this->db->query("select * from user limit 0,5"); //Line 30 error as in my IDE located in this line
         return $qu开发者_如何学编程ery->result();
     }
}

This is my controller: home.php

class home extends Controller {

function index() {

    parent::Controller();

}
function alluser() {
    $this->load->model('User');
    $result = $this->User->showusers();
    if ($result->num_rows()>0) {
        foreach ($result as $row) {
            echo "ID:".$row->userid." ".$row->userpenname."<br />";
            echo $row->userfirstname." ".$row->userlastname."<br />";
        }
      }
   }
}

it showing error:

A PHP Error was encountered

Severity: Notice

Message: Undefined property: User::$db

Filename: models/user.php

Line Number: 30

Fatal error: Call to a member function query() on a non-object in

G:\xampp\htdocs\fiksi\system\application\models\user.php on line 30

Line 30 see comment above...


You have to load the db library first. In autoload.php add :

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

Also, try renaming User model class for "User_model".


It solved throung second parameter in Model load:

$this->load->model('user','User');

first parameter is the model's filename, and second it defining the name of model to be used in the controller:

function alluser() 
{
$this->load->model('User');
$result = $this->User->showusers();
}


function user() { 

       parent::Model(); 

} 

=> class name is User, construct name is User.

function User() { 

       parent::Model(); 

} 
0

精彩评论

暂无评论...
验证码 换一张
取 消