2012-08-06 44 views
1

基本上,我已經是這樣的:笨 - 將數據保存在模型

class Database extends CI_Model 
{ 
    function __construct() 
    { 
     parent::__construct(); 
    } 

    function connect($connection_infos) 
    { 
     $db = @new mysqli($connection_infos['host'], $connection_infos['username'], 
       $connection_infos['password'], $connection_infos['database']); 
     if (mysqli_connect_errno()) 
      return FALSE; 
     else 
      return TRUE; 
    } 
} 

該模型加載到控制器的功能:

class Management extends CI_Controller 
{ 

    static $dbs = array(
       'ref' => array(
        'connected' => FALSE, 
       ), 
       'dest' => array(
        'connected' => FALSE, 
       ) 
      ); 

    function connection() 
    { 
     $this->load->library('form_validation'); 
     $data = array(); 

     $this->form_validation->set_rules('host', 'Hostname', 'required'); 
     $this->form_validation->set_rules('username', 'Username', 'required'); 
     $this->form_validation->set_rules('database', 'Database', 'required'); 
     if (!$this->form_validation->run()) { 
      $data['dbs'] = self::$dbs; 
     } else { 
      $this->load->model('database'); // Here I load the model 
      $connection_infos = array(
        'host' => $this->input->post('host'), 
        'username' => $this->input->post('username'), 
        'password' => $this->input->post('password'), 
        'database' => $this->input->post('database'), 
       ); 
      if ($this->database->connect($connection_infos)) { 
       self::$dbs['ref']['connected'] = TRUE; 
       $data['dbs'] = self::$dbs; 
      } 
     } 
     $this->load->view('dashboard', $data); 
    } 
} 

因此,這裏是我做過什麼:

在我看來的表單驗證中,我從我的控制器調用函數connection。該功能加載Database型號,並調用模型的功能connect

我的問題是:如果我想讓我的模型中的其他功能發出其他請求,我是否會被迫每次都打開一個連接?如果是,我如何「存儲」連接憑證?

謝謝!

+1

您知道Codeigniter有一個數據庫幫助程序庫嗎?其中,您可以創建一個自定義模型,包含所有可以重複使用的功能和請求,而不必擔心自己創建數據庫類,或擔心在需要時連接等。 – chris 2012-08-06 16:11:56

+0

我有一個問題,你爲什麼使用Codeignitor? – Red 2012-08-06 17:46:23

+0

@chris當然是我了,但在這裏我想動態地連接到數據庫,具體取決於用戶在表單中放置的內容。 – 2012-08-07 07:04:15

回答

3

根據我所看到的,您需要前往CI文檔並在database library上閱讀lot

除了本教程中介紹的基本語法/語義之外,名爲「數據庫」的模型是不合邏輯的,並不是一個很好的命名選擇。在CodeIgniter的範圍內,您應該嘗試使模型僅與一個數據庫表格特別相關。

至於實際的數據庫連接,它在CI_Model類中作爲成員對象$db自動處理。我建議閱讀CI中modelsdatabase connections的文檔。

因此,如果正確設置了所有設置,加載正確編碼的模型將爲您提供模型內的自動數據庫連接,但無論何時都可以重複使用。

+0

我知道所有這些東西,但在這裏我會喜歡使用用戶放置在表單中的憑據動態連接到數據庫。 – 2012-08-07 07:04:58