2016-08-12 1 views
0

동적으로 데이터베이스에서 다른 이름으로 동적으로 전환하고 싶습니다. 이름이 동적으로 사용자에 의해 부여되었습니다. 내가 할 dbforge 싶어, 당신이 볼 수 있듯이DB Forge, Code Igniter 및 동적 데이터베이스 선택

//database.php 

$active_group = 'default'; 
$query_builder = TRUE; 

$db['default'] = array(
    'dsn' => '', 
    'hostname' => 'localhost', 
    'username' => 'root', 
    'password' => '', 
    'database' => 'firstbase', 
    'dbdriver' => 'mysqli', 
    'dbprefix' => '', 
    'pconnect' => FALSE, 
    'db_debug' => (ENVIRONMENT !== 'production'), 
    'cache_on' => FALSE, 
    'cachedir' => '', 
    'char_set' => 'utf8', 
    'dbcollat' => 'utf8_general_ci', 
    'swap_pre' => '', 
    'encrypt' => FALSE, 
    'compress' => FALSE, 
    'stricton' => FALSE, 
    'failover' => array(), 
    'save_queries' => TRUE 
); 

$db['newbase'] = $db['default']; 

는 'newbase는'

//Install_model Model 
    echo "<BR>Active db :".$this->db->database; 
    $this->createDB($database); 
    $this->db->close(); 

    //now $database is created 

    //load the 'newbase' group and assign it to $this->newDb 
    $this->newDb = $this->load->database('newbase', TRUE); 

    //this will output 'firstbase' 
    echo "<BR>so far, the active db is :".$this->newDb->database; 
    $this->newDb->database=$database; 
    //now this will output the $database string 
    echo "<BR>and now the active db is :".$this->newDb->database; 

이제 기본 설정의 단순 복사본입니다 : 여기

내 코드의 일부 표시하는 조각이다 이 새 데이터베이스에서 사용됩니다.

$linkfields = array(
      'table_id' => array(
        'type' => 'VARCHAR', 
        'constraint' => '15' 
      ), 
      'something' => array(
        'type' => 'VARCHAR', 
        'constraint' => '15', 
        'unique' => TRUE, 
      ), 
     ); 

     //according to the manual, we "give" our new DB to dbforge 
     $this->myforge = $this->load->dbforge($this->newDb, TRUE); 
     $this->myforge->add_field($linkfields); 
     $this->myforge->add_key('table_id', TRUE); 
     $this->myforge->create_table('Link'); 

이것은 작동하지만 ... 'firstbase'에서 테이블이 만들어졌습니다! 그리고로드 된 데이터베이스가 두 번째 것입니다. 이 문제를 어떻게 해결할 수 있습니까?

편집 # 1

은 분명히, $this->newDb->database=$database;은 지속되지 않습니다. 연결이 닫히고 다시 열린 경우 $this->newDb->database은 데이터베이스 구성 파일에 처음에 제공된 값을가집니다. 그러나 이것이 내가 그 결말을 닫지 않았기 때문에 내가 그 결과를 얻는 이유를 설명하지는 않습니다.

구성 파일에 $db['newbase']['database'] = '';을 추가하면 # 1046 오류가 발생합니다. 데이터베이스가 선택되지 않았습니다. 이렇게하면 $this->newDb->database이 dbforge에서 사용되지 않는다는 사실이 확인됩니다. dbforge는 대신 하드 코딩 된 값을 사용합니다.

답변

0

답변에 관심이있는 분들은 여기 있습니다.

트릭은 아주 간단합니다. 동시에 2dbs를 열지 않기 때문에 기본 db를 처리하는 것처럼 $ this를 사용했습니다. config 파일에서 'database'필드가 비어있는 'newbase'라는 두 번째 그룹이 있다고 가정 해 보겠습니다.

사용자는 설치 과정에서이 이름을 제공합니다.

그래서, DB를 생성하고 접속이 종료되면 :

$this->load->database('newbase', True);  
$this->db->database = '$database'; 

사용 $this->db->database 처리되고 어떤 DB를 알기 위해.

는 위와 같이 $의 linkfields를 선언하고 단순히 dbforge 클래스 전화 :

$this->load->dbforge(); 
$this->dbforge->add_field($linkfields); 
$this->dbforge->add_key('table_id', TRUE); 
$this->dbforge->create_table('Link'); 
관련 문제