新手求教
A PHP Error was encounteredSeverity: NoticeMessage: 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');
想问一下,这两者有区别吗?区别是什么? 第一种,按需加载
第二种,应用启动就加载。 楼上正解,话说如果用了autoload加载db,会不会拖慢程序? 我试了第二种方法可以,但为什么第一种方法不行呢? 我是这样写的
class Test_m extends CI_Model
{
function _construct()
{
parent::_construct();
$this->load->database();
}
} 模式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();我放在模式里不行,而放在控制器里可以呢? 最好用第二种方法:修改application\\config\\autoload.php文件,如下:
将 $autoload['libraries'] = array();
改为:$autoload['libraries'] = array('database');
程序自动加载,避免重复访问数据库
页:
[1]