为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
茅侃侃 2022-07-22 18:50:05
我正在为我的应用程序创建一个 Web 安装程序。在安装程序中,我将允许用户输入服务器、用户名、密码和数据库名称的值。现在使用这个值,我将如何验证我的应用程序是否可以与数据库建立连接注意:我没有使用该config/database.php文件。相反,我将使用用户发布的数据并测试连接。如果成功,会将这些值写入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}
查看完整描述

2 回答

?
千万里不及你

TA贡献1784条经验 获得超9个赞

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


$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

}

在加载器类参考之后:


返回:如果 $return 设置为 TRUE,则加载 CI_DB 实例或 FALSE 失败,否则 CI_Loader 实例(方法链接)


查看完整回答
反对 回复 2022-07-22
?
暮色呼如

TA贡献1853条经验 获得超9个赞

好的。我想到了。


使用TRUEorFALSE作为第二个参数$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

}


查看完整回答
反对 回复 2022-07-22
  • 2 回答
  • 0 关注
  • 88 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信