Yii2 创建数据库连接

Abh*_*ran 3 php database yii2

我想以编程方式创建数据库连接,而不使用配置文件。我有一个表单,用户在其中输入数据库详细信息,例如hostnameusername和。根据这些详细信息,建立新的测试连接,如果通过,则应生成必要的文件。这是我尝试过的:passworddatabase 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();
}
Run Code Online (Sandbox Code Playgroud)

我已经一次又一次地对此进行了测试,即使配置正确,它也会出现错误。感谢所有的帮助。提前致谢!

小智 5

您可以这样定义一个新连接:

   $db = new yii\db\Connection([
   'dsn' => 'mysql:host=localhost;dbname=example',
   'username' => 'root',
   'password' => '',
   'charset' => 'utf8',
]); 

$db->open();
Run Code Online (Sandbox Code Playgroud)

建立数据库连接后,可以执行如下 SQL 语句,例如:

 $command = $db->createCommand('SELECT * FROM post');
 $posts = $command->queryAll();

 // or 

 $command = $connection->createCommand('UPDATE post SET status=1');
 $command->execute();
Run Code Online (Sandbox Code Playgroud)

你可以看看这个文档和指南

http://www.yiiframework.com/doc-2.0/guide-db-dao.html

http://www.yiiframework.com/doc-2.0/yii-db-connection.html