I want to create a database connection programmatically without using the config file. I have a form wherein the user enters the database details like the hostname
, username
, password
and the database name
. On the basis of these details a new test connection is made and if it passes it should generate the necessary files.
This is what I have tried:
// Create Test DB Connection
Yii::$app->set('id', [
'class' => 'yiidbConnection',
'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'] = 'yiidbConnection';
$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();
}
I have tested this again and again and even with correct configurations it is giving an error.
All the help is appreciated. Thanks in advance!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…