Yii2 Create Database Connection

2019-02-26 00:44发布

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'    => '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();
}

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!

2条回答
We Are One
2楼-- · 2019-02-26 01:06

You can define a new connection this way:

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

$db->open();

After the DB connection is established, one can execute SQL statements like the following eg:

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

 // or 

 $command = $connection->createCommand('UPDATE post SET status=1');
 $command->execute();

you can look at this for doc and guide

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

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

查看更多
再贱就再见
3楼-- · 2019-02-26 01:19

I realised my mistake. When using Yii::$app->set() for setting up the db connection, you have to even manually open the connection using Yii::$app->db->open(). Yii doesn't open up the connection for you.

查看更多
登录 后发表回答