Yii2 Create Database Connection

后端 未结 2 1498
温柔的废话
温柔的废话 2021-01-21 18:14

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,

2条回答
  •  感情败类
    2021-01-21 18:37

    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

提交回复
热议问题