2012-11-02 37 views
2

我試圖在codeigniter中向mysql插入數據。 Controller類:調用一個非對象的成員函數insert(),codeigniter

class Ci_insert extends CI_Controller 
    { 
     function __construct() 
     { 
      parent::__construct(); 
     } 

     function index() 
     { 
      $data = array(
          "USN" => "TRE5rCS89G", 
          "name" => "NITISH DOLAKASHARIA", 
          "branch" => "CS" 
         ); 

      $this->load->model('ci_insert_model'); 

      $this->ci_insert_model->addToDb($data); 
     } 

    } 

模型類:

class ci_insert_model extends CI_Model 
    { 
     function __construct() 
     { 
      parent::__construct(); 
     } 
     function addToDb($data) 
     { 

      //var_dump($data); 
      $this->db->insert('class_record',$data); 
     } 
    } 

但是,當我試圖運行的代碼,它顯示Fatal error: Call to a member function insert() on a non-object in C:\wamp\www\CodeIgniter\application\models\ci_insert_model.php on line 12

上面的代碼有什麼問題?

+2

不要使用'ci_'爲前綴的一類,那是留給笨本地類。從文檔:*請注意,所有本機CodeIgniter庫前綴CI_所以不要使用它作爲您的前綴。* – Esailija

+1

是你自動加載數據庫庫? – max

回答

1

試用。

控制器:insert.php

class Insert extends CI_Controller 
{ 
    function __construct() 
    { 
     parent::__construct(); 
    } 

    function index() 
    { 
     $data = array(
         "USN" => "TRE5rCS89G", 
         "name" => "NITISH DOLAKASHARIA", 
         "branch" => "CS" 
        ); 

     $this->load->model('insert_model'); 

     $this->insert_model->addToDb($data); 
    } 

} 

型號:insert_model.php類的

class Insert_model extends CI_Model 
{ 
    function __construct() 
    { 
     parent::__construct(); 
    } 
    function addToDb($data) 
    { 

     //var_dump($data); 
     $this->db->insert('class_record',$data); 
    } 
} 

請寫出資本第一後,沒有像ci_添加前綴。

8

你錯過$this->load->database();

$this->db->method_name();加載數據庫庫時纔會工作。

如果您計劃在整個應用程序中使用數據庫,我會建議將它添加到autoload.php/application/config/

正如其他人提到的,從您的類名稱中刪除CI_前綴。 CI_保留給框架類。

3

您必須在'$this->db->insert()'或 之前的模型中使用'$this->load->library('database')'自動加載數據庫庫。轉到配置文件夾選擇autoload.php搜索$ autoload ['libraries']並用數組('database')替換空的數組(')。

3

添加自動加載庫在配置文件夾打開autoload.php,並設置$autoload['libraries'] = array('database');

相關問題