配置database.php文件后如何在codeigniter中正确构建连接?

时间:2014-06-03 11:57:41

标签: codeigniter

这是我的控制器代码,用于以编程方式设置主机名,用户名,密码,database_name&它在我的代码中正常工作

  function submit_installation()
    {
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->database();

    if($_POST)
    {
        //--------------------to config database file----------------------
        $old_hostname = '$db[\'default\'][\'hostname\']';
        $old_username = '$db[\'default\'][\'username\']';
        $old_password = '$db[\'default\'][\'password\']';
       $old_database = '$db[\'default\'][\'database\']';
        $fileName = "./application/config/database.php";


        $file = file($fileName);

        foreach( $file as $key=>$line ) {
            if( false !== strpos($line, $old_hostname) )
            {
                $file[$key]=$old_hostname."='".$_POST['hostname']."';\n";
            }
            elseif( false !== strpos($line, $old_username) )
            {
                $file[$key]=$old_username."='".$_POST['username']."';\n";
            }
            elseif( false !== strpos($line, $old_password) )
               {
                  $file[$key]=$old_password."='".$_POST['password']."';\n";
              }
            elseif( false !== strpos($line, $old_database) )
            {
                $file[$key]=$old_database."='".$_POST['database']."';\n";
            }
        }


        file_put_contents($fileName, $file);
}
}

在database.php中执行控制器文件&之后的代码显示数据库设置。在database.php文件中进行的更改。

    <?php

$active_group = 'default';
$active_record = TRUE
 $db['default']['hostname']='xxx';
 $db['default']['username']='abc';
 $db['default']['password']='abc';
 $db['default']['database']='xyz';
    $db['default']['dbprefix'] = '';
    $db['default']['pconnect'] = TRUE;
    $db['default']['db_debug'] = FALSE;
    $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;

那么如何检查数据库连接是否使用后端代码?

1 个答案:

答案 0 :(得分:1)

我想你必须尝试这个:

$db_host        = 'localhost';
$db_user        = 'abc';
$db_pass        = 'xyz';
$db_database    = 'qwerty'; 
$link = mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');

这个方法很简单。