mada
mada

Reputation: 31

How to connect to a database without the config file in Yii2?

I am using, for the same problem, the code which is given in this question Yii2 Create Database Connection.

I realise the $config variable is no longer the one in the web.php file, from the "config" folder, and that he is changing $configin his Configuration::setConfig() function.

My question for those more experienced than me in Yii is what should I write

I'm sorry if my question is not clear enough. Please ask for details in the comments if needed. Thank you!

Upvotes: 1

Views: 1744

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133370

You can define a new connection this way

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

$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

Upvotes: 3

Related Questions