我希望能够通过编程的方式创建数据库连接而不使用配置文件。我有一个表单,用户可以输入数据库的详情,比如 hostname
, username
, password
, 以及 database name
。根据这些信息,我们可以尝试建立一个新的测试连接,如果成功,就应该生成必要的文件。
以下是我尝试过的方法:
// Create Test DB Connection
Yii::$app->set('id', [
'class' => 'yii\db\Connection',
'dsn' => $dsn,
'username' => $form->username,
'password' => $form->password,
'charset' => 'utf8'
]);
try {
// Check DB Connection
if (Yii::$app->db->getIsActive()) {
// Write Config
$config['components']['db']['class'] = 'yii\db\Connection';
$config['components']['db']['dsn'] = $dsn;
$config['components']['db']['username'] = $username;
$config['components']['db']['password'] = $password;
$config['components']['db']['charset'] = 'utf8';
Configuration::setConfig($config);
$success = TRUE;
return $this->redirect(['init']);
}else{
$errorMsg = 'Incorrect Configurations';
}
} catch (Exception $e) {
$errorMsg = $e->getMessage();
}
我已经反复测试过了,即使配置正确,它仍然会出现错误。 非常感谢您的帮助。提前致谢!