Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
806 views
in Technique[技术] by (71.8m points)

php - Yii2 Create Database Connection

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can define a new connection this way:

   $db = new yiidbConnection([
   '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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...