3

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 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.