使用php脚本配置config / database.php文件

时间:2013-07-16 06:42:25

标签: codeigniter database-connection

我的控制器中有一个脚本,如下所示:

if($this->db->query("CREATE DATABASE IF NOT EXISTS db_ecommerce"))
        {
                $sql=file_get_contents('./databse_backup/backup.sql');
                foreach (explode(";\n", $sql) as $sql) 
                {
                    $sql = trim($sql);
                    //echo  $sql.'<br/>============<br/>';
                        if($sql) 
                    {
                        $this->db->query($sql);
                    } 
                }  
        }

它创建一个数据库,然后运行备份sql文件。

我的问题是我们需要事先配置config / database.php文件。

首先,我希望运行此脚本,之后应更改database.php文件。

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'username';
$db['default']['password'] = 'password';
$db['default']['database'] = 'db_name';

因为它现在为localhost,

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'db_name';

1 个答案:

答案 0 :(得分:2)

一种方法是在您的安装文件夹中安装“模板文件”,例如: 恩。 database.php中

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = '<?php echo $hostname;?>';
$db['default']['username'] = '<?php echo $username;?>';
$db['default']['password'] = '<?php echo $password;?>';
$db['default']['database'] = '<?php echo $database;?>';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '<?php echo $prefix;?>';
$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';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

然后你可以获取db连接的值(例如从表单中获取)并在codeigniter应用程序中写入新文件(application / config / database.php)

离。

$settings['hostname']   = $this->input->post('hostname');
$settings['username']   = $this->input->post('username');
$settings['password']   = $this->input->post('password');
$settings['database']   = $this->input->post('database');
$settings['prefix']     = $this->input->post('prefix');     

$file_contents      = $this->load->view('templates/database', $settings, true);


write_file($_SERVER['DOCUMENT_ROOT'].'application/config/database.php', $file_contents);