Codeigniter 3 - 即时测试数据库连接 - 不使用 config/database.php 文件

Codeigniter 3 - Test database connection on the fly - Not using config/database.php file

我正在为我的应用创建网络安装程序。在安装程序中,我将允许用户输入服务器、用户名、密码和数据库名称的值。

现在使用这个值,我将如何验证我的应用程序是否可以与数据库建立连接

Note: I'm not making use of the config/database.php file. Instead, I'll make use of the posted data by the user and test the connection. If successful, will write those values to the config/database.php

我的控制器代码如下:

$host = $this->input->post('dbserver');
$username = $this->input->post('dbusername');
$password = $this->input->post('dbpassword');
$name = $this->input->post('dbname');

if(<can connect with the database using the above>) // <---- This is what I'm looking for
{
   // write to the config/database.php file
}

根据 codeigniter documentation,您可以使用手动连接到数据库执行以下操作:

$config['hostname'] = $this->input->post('dbserver');
$config['username'] = $this->input->post('dbusername');
$config['password'] = $this->input->post('dbpassword');
$config['database'] = $this->input->post('dbname');
$config['dbdriver'] = {driver_to_use};
$config['dbprefix'] = {prefix};
$config['pconnect'] = {bool};
$config['db_debug'] = {bool};
$config['cache_on'] = {bool};
$config['cachedir'] = {cachedir};
$config['char_set'] = {char_set};
$config['dbcollat'] = {dbcollat};

if($this->load->database($config, TRUE))
{
  // Write the db config file
}

loader class reference 之后:

Returns : Loaded CI_DB instance or FALSE on failure if $return is set to TRUE, otherwise CI_Loader instance (method chaining)

好的。我想到了。

使用 TRUEFALSE 作为 $this->load->database() 的第二个参数总是返回一个对象,因此检查 if($this->load->database()) 是徒劳的,因为它总是评估为 TRUE 即使凭据错误。

所以我继续这样做了:

@$this->load->database($config, FALSE, TRUE); // using @ to avoid warnings in case of wrong credentials
if(@$this->db->initialize()) // again use @ to avoid error messages
{
   // now this verifies it truly connected
}