用户
 找回密码
 入住 CI 中国社区
搜索
查看: 1628|回复: 6
收起左侧

新手求教

[复制链接]
发表于 2013-2-5 11:20:58 | 显示全部楼层 |阅读模式
A PHP Error was encounteredSeverity: Notice
Message: Undefined property: User:db
Filename: core/Model.php
Line Number: 51


解决方法有两种:

第一种:在你的Model类的构造方法中,加入 $this->load->database();   如下:
     public function MUser(){          parent::__construct();
         $this->load->database();
     }
第二种方法:修改application\config\autoload.php文件,如下:
    将 $autoload['libraries'] = array();
    改为:  $autoload['libraries'] = array('database');

想问一下,这两者有区别吗?区别是什么?
发表于 2013-2-5 11:40:52 | 显示全部楼层
第一种,按需加载
第二种,应用启动就加载。
发表于 2013-2-5 12:33:44 | 显示全部楼层
楼上正解,话说如果用了autoload加载db,会不会拖慢程序?
 楼主| 发表于 2013-2-5 13:56:12 | 显示全部楼层
我试了第二种方法可以,但为什么第一种方法不行呢?
 楼主| 发表于 2013-2-5 13:56:51 | 显示全部楼层
我是这样写的
class Test_m extends CI_Model
{
        function _construct()
        {
                parent::_construct();
                $this->load->database();
        }
}
 楼主| 发表于 2013-2-5 14:38:25 | 显示全部楼层
模式Test_m
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Test_m extends CI_Model
{
        function _construct()
        {
                parent::_construct();
               
                $this->load->database();
        }

        function user_insert($arr)
        {
                $this->db->insert("user",$arr);
        }
       
        function user_update($id,$arr)
        {
                $this->db->where("id",$id);
                $this->db->update("user",$arr);
        }
}

控制器User
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {

        function insert()
        {
                $this->load->model("test_m");
               
                $this->load->database();
               
                $arr=array("uname"=>"u2","upass"=>"123456");
               
                $this->test_m->user_insert($arr);
        }
}

我想问一下,为什么$this->load->database();我放在模式里不行,而放在控制器里可以呢?
发表于 2013-2-8 14:22:32 | 显示全部楼层
最好用第二种方法:修改application\\config\\autoload.php文件,如下:
    将 $autoload['libraries'] = array();
    改为:  $autoload['libraries'] = array('database');

程序自动加载,避免重复访问数据库

本版积分规则