我不确定我的代码有什么问题.......它在加载模型时导致错误....... 请帮忙........... 我的控制器
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Exams extends CI_Controller {
public function index(){
$ob = new exam_class();
$ob->set_exam(0,'Html exam','1','20');
$ob->create_exam();
echo 'success';
}
}
class exam_class{
private $id;
private $title;
private $catagory;
private $timeLength;
function set_exam($id,$title,$catagory,$timeLength){
$this->id = $id;
$this->title = $title;
$this->catagory = $catagory;
$this->timeLength = $timeLength;
}
function create_exam(){
$this->load->model('examModel');
$this->examModel->create_exams($title,$catagory,$timeLength);
}
}
模型
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class ExamModel extends CI_Model {
public function create_exams($title,$catagory,$timeLength){
$data = array(
'title' => $title ,
'catagory' => $catagory ,
'timeLength' => $timeLength
);
$this->db->insert('exams', $data);
}
}
错误 遇到PHP错误
严重性:注意
消息:未定义的属性:exam_class :: $ load
文件名:controllers / exams.php
行号:26
致命错误:在第26行的C:\ xampp \ htdocs \ exam \ application \ controllers \ exams.php中的非对象上调用成员函数model()
答案 0 :(得分:2)
您不应该在文件中放置多个类。控制器应该是这样的。
class Exams extends CI_Controller {
private $id;
private $title;
private $catagory;
private $timeLength;
public function __construct()
{
parent::__construct();
$this->load->model('examModel');
}
public function index(){
$this->set_exam(0,'Html exam','1','20');
$this->create_exam();
echo 'success';
}
function set_exam($id,$title,$catagory,$timeLength){
$this->id = $id;
$this->title = $title;
$this->catagory = $catagory;
$this->timeLength = $timeLength;
}
function create_exam(){
$this->examModel->create_exams($title,$catagory,$timeLength);
}
}
答案 1 :(得分:1)
与@shin一起,我希望包括转到此文件
....\testproject\application\config\autoload.php
并编辑此内容以添加模型
$autoload['model'] = array('modelName1','modelName2');
并从任何控制器随时加载模型。这将自动加载您的模型。无需添加
$this->load->model('modelName');
答案 2 :(得分:0)
提示:保持简单
在您的控制器中:
public function __construct()
{
parent::__construct();
$this->load->model('examModel');
}
public function index()
{
$exam_data = $this->process_exam_data(0,'Html exam','1','20');
$insert_status = $this->examModel->create_exams($exam_data);
if($insert_status===TRUE){
echo "Exam Insert Successful!";
}
else{
echo "Exam Insert Failed";
}
}
public function process_exam_data($id, $title, $category, $timelength)
{
// Do whatever you want with the data, calculations etc.
// Prepare your data array same as to be inserted into db
$final_data = array(
'title' => $processed_title,
'catagory' => $processed_category,
'timeLength' => $processed_time
);
return $final_data;
}
在你的模特中:
public function create_exams($data)
{
$result = $this->db->insert('exams', $data); // Query builder functions return true on success and false on failure
return $result;
}
您的index
函数是执行调用的主函数,而所有处理工作都在process_exam_data
函数中完成。
祝你有愉快的一天:)