2016-02-19 103 views
1

我想使用CodeIgniter和DBForge來創建一個多租戶應用程序。我將在中央數據庫中創建一個「用戶」表,用於存儲用戶的名稱和數據庫的名稱。PHP CodeIgniter每個用戶一個數據庫

我遇到的問題是創建個人數據庫和他們的表。這裏的代碼片段:沒有任何問題,創建

if ($this->dbforge->create_database($db_name)) 
    { 

      echo 'Database created!'; 

      // an array of fields 
      $fields = array(
        'name' => array(
          'type' => 'VARCHAR', 
          'constraint' => '100', 
        ), 
      ); 

      // set them up for the new table 
      $this->dbforge->add_field($fields); 

      // create the new table in the new db 
      $this->dbforge->create_table('items'); 

    } 

數據庫$ DB_NAME但是當我創建表「項目」,這是對我的中央數據庫中創建這不是我想要的。

回答

0

嗨,當你試圖創建表,它正在你的默認連接數據庫中創建表,你必須重新連接你的數據庫與用戶創建的數據庫,並將該連接的數據庫對象傳遞給$ this-> db並再次獲取比它會在用戶數據庫中創建表在這裏如何在用戶數據庫中創建表

if ($this->dbforge->create_database($db_name)) { 

      echo 'Database created!'; 
      // an array of fields 

      $config['hostname'] = "localhost"; 
      $config['username'] = "root"; 
      $config['password'] = ""; 
      $config['database'] = $db_name; 
      $config['dbdriver'] = "mysql"; 
      $config['dbprefix'] = ""; 
      $config['pconnect'] = FALSE; 
      $config['db_debug'] = TRUE; 
      $config['cache_on'] = FALSE; 
      $config['cachedir'] = ""; 
      $config['char_set'] = "utf8"; 
      $config['dbcollat'] = "utf8_general_ci"; 

      $this->db = $this->load->database($config, TRUE); //<- magic start from here 

      $this->load->dbforge(); 

      $fields = array(
       'name' => array(
        'type' => 'VARCHAR', 
        'constraint' => '100', 
       ), 
      ); 

      // set them up for the new table 
      $this->dbforge->add_field($fields); 

      // create the new table in the new db 
      $this->dbforge->create_table('items'); 
     } 

讓你的代碼更乾淨創建的應用程序/配置一個user_db.php文件,並把用戶配置那裏,每次$配置['數據庫']在您的代碼

+0

謝謝umefarooq - 這是完美的,正在做我所需要的! – Robl

+0

比請接受這個答案並向上 – umefarooq

相關問題