如何替换Codeigniter中的数据库配置?

Waq*_*mad 5 php codeigniter

我为我的网站生气了。但我不如何更换hostnameusernamepassworddatabase。与来自输入字段的值。这是config/database.php文件中的代码。

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'db_host',
    'username' => 'db_user',
    'password' => 'db_pass',
    'database' => 'db_name',
    '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
);
Run Code Online (Sandbox Code Playgroud)

但是这段代码给了我这个错误。

在此处输入图片说明

和中的此代码controller

function configure_database() {
    // write database.php
    $data_db = file_get_contents('./application/config/database.php');
   // session_start();
    $data_db = str_replace('db_name',   $_POST['dbname'],   $data_db);
    $data_db = str_replace('db_user',   $_POST['username'], $data_db);
    $data_db = str_replace('db_pass',   $_POST['password'], $data_db);
    $data_db = str_replace('db_host',   $_POST['hostname'], $data_db);
    file_put_contents('./application/config/database.php', $data_db);
  }
Run Code Online (Sandbox Code Playgroud)

Has*_*ana 2

您可以config/database.php按如下方式格式化:

$db['default']['username'] = "%USERNAME%";
$db['default']['password'] = "%PASSWORD%";
$db['default']['database'] = "%DATABASE%";
$db['default']['hostname'] = "%HOSTNAME%";
$db['default']['dbdriver'] = "mysqli";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
Run Code Online (Sandbox Code Playgroud)

然后使用以下方法写入它:

function configure_database() {
    // write database.php
    $data_db = file_get_contents('config/database.php');
    // session_start();
    $temporary = str_replace("%DATABASE%", $_POST['dbname'],   $data_db);
    $temporary = str_replace("%USERNAME%", $_POST['username'], $temporary);
    $temporary = str_replace("%PASSWORD%", $_POST['password'], $temporary);
    $temporary = str_replace("%HOSTNAME%", $_POST['hostname'], $temporary);
    // Write the new database.php file
    $output_path = './application/config/database.php';
    $handle = fopen($output_path,'w+');
    // Chmod the file, in case the user forgot
    @chmod($output_path,0777);
    // Verify file permissions
    if(is_writable($output_path)) {
        // Write the file
        if(fwrite($handle,$temporary)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上它会检查每一行是否匹配,然后用发布的数据替换它们,最后再次将其写入数据库配置。

参考:CodeIgniter安装程序