2

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 2

8

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
  • 1
    Well, that's fancy! Commented Dec 3, 2018 at 23:32
1

I wrote a free plugin to allow you to do exactly that: Connect

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.