我想在不使用配置文件的情况下以编程方式创建数据库连接。我有一个表单,用户可以在其中输入数据库详细信息,例如 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();
}
我已经一次又一次地测试了这个,即使配置正确,它也会出错。 感谢所有帮助。提前致谢!
最佳答案
你可以这样定义一个新的连接:
$db = new yii\db\Connection([
'dsn' => 'mysql:host=localhost;dbname=example',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]);
$db->open();
DB连接建立后,可以执行如下SQL语句eg:
$command = $db->createCommand('SELECT * FROM post');
$posts = $command->queryAll();
// or
$command = $connection->createCommand('UPDATE post SET status=1');
$command->execute();
你可以看看这个文档和指南
关于php - Yii2 创建数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28254001/