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.

6

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... }}
| improve this answer | |
  • 1
    Well, that's fancy! – andrew.welch Dec 3 '18 at 23:32
1

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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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