config.php
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'exampleUser1';
$db['default']['password'] = '12345678';
$db['default']['database'] = 'exampleDB1';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = FALSE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = TRUE;
$db['otherdb']['hostname'] = "localhost";
$db['otherdb']['username'] = 'exampleUser2';
$db['otherdb']['password'] = '12345678';
$db['otherdb']['database'] = 'exampleDB2';
$db['otherdb']['dbdriver'] = "mysql";
$db['otherdb']['dbprefix'] = "";
$db['otherdb']['pconnect'] = FALSE;
$db['otherdb']['db_debug'] = TRUE;
$db['otherdb']['cache_on'] = FALSE;
$db['otherdb']['cachedir'] = "";
$db['otherdb']['char_set'] = "utf8";
$db['otherdb']['dbcollat'] = "utf8_general_ci";
$db['otherdb']['swap_pre'] = "";
$db['otherdb']['autoinit'] = TRUE;
$db['otherdb']['stricton'] = TRUE;
控制器
$otherdb = $this->load->database('otherdb', TRUE);
$this->data['student_count'] = $otherdb->professor_m->ActiveStudent_count();
模式
function ActiveStudent_count() {
$otherdb->from('student');
$otherdb->join('classes', 'student.classesID = classes.classesID', 'LEFT');
$otherdb->join('sub_courses', 'student.sub_coursesID = sub_courses.sub_coursesID', 'LEFT');
$otherdb->join('invoice', 'student.studentID = invoice.studentID', 'LEFT');
$otherdb->where('student.adminID',102);
$otherdb->where('classes.status', 1);
$otherdb->where('invoice.feetype', 'clg');
$otherdb->where('student.status',1);
$otherdb->where('invoice.student_position', 1);
$otherdb->group_by('invoice.studentID');
$adminID = $this->session->userdata("adminID");
$usertype = $this->session->userdata("usertype");
$loginuserID = $this->session->userdata("loginuserID");
if ($usertype=='Teacher')
{
$otherdb->where('student.counsellor',$loginuserID);
$otherdb->where('invoice.userID',$loginuserID);
}
$query = $otherdb->get();
return $query->num_rows();
}
view/index.php
<?php
echo $student_count;
?>
在这段代码中,我在同一台服务器上有两个不同的数据库。现在,我只是在config.php
中创建另一个数据库连接,在我的控制器中,我从professor_m
模式中获取数据,但当我在视图文件中获取数据时。然后它抛出一个错误,即Message: Undefined property: CI_DB_mysql_driver::$professor_m
。那么,我该怎么修呢?请帮帮我。
谢谢
您应该在function ActiveStudent_count() {
内部使用$otherdb = $this->load->database('otherdb', TRUE);
,或者在模型构造函数内部使用,但不能在控制器中使用。
像一样更新控制器
$this->load->model("math_model","professor_m");
$this->data['student_count'] = $this->professor_m->ActiveStudent_count();
控制器中调用模型的简单代码:
$data['student_count'] = $this->professor_m->ActiveStudent_count();
并在professor_m
模型ActiveStudent_count()
方法中完成此代码:
$this->otherdb = $this->load->database('exampleDB2', TRUE);
$this->otherdb->query() // just put your query here like what you want
希望这对你有用