Reputation: 31
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 $config
in his Configuration::setConfig()
function.
My question for those more experienced than me in Yii is what should I write
db
field (or in the db.php file) to "create a database connection programmatically without using the config file" ?Configuration::setConfig()
to properly configure the application?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
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