Is there a way to access another database outside of the one Craft uses for its content? I need to able to access data fields from an external source for a project I'm working on.
2 Answers
From your config/app.php
file you could do something like this:
return [
'components' => [
'otherDb' => [
'class' => craft\db\Connection::class,
'driverName' => 'mysql',
'dsn' => 'mysql:host=localhost;dbname=mydb;port=3306;',
'username' => 'myuser',
'password' => 'mypass',
'charset' => 'utf8',
'tablePrefix' => '',
'enableSchemaCache' => !YII_DEBUG,
],
],
]
You might not need all of those depending on what you're doing.
Then from PHP, could access it like:
Craft::$app->otherDb->createCommand(...);
And from a template:
{{ craft.app.otherDb... }}
-
1