<p>From your <code>config/app.php</code> file you could do something like this:</p>

<pre><code>return [
    'components' =&gt; [
        'otherDb' =&gt; [
            'class' =&gt; craft\db\Connection::class,
            'driverName' =&gt; 'mysql',
            'dsn' =&gt; 'mysql:host=localhost;dbname=mydb;port=3306;',
            'username' =&gt; 'myuser',
            'password' =&gt; 'mypass',
            'charset' =&gt; 'utf8',
            'tablePrefix' =&gt; '',
            'enableSchemaCache' =&gt; !YII_DEBUG,
        ],
    ],
]
</code></pre>

<p>You might not need all of those depending on what you're doing.</p>

<p>Then from PHP, could access it like:</p>

<pre><code>Craft::$app-&gt;otherDb-&gt;createCommand(...);
</code></pre>

<p>And from a template:</p>

<pre><code>{{ craft.app.otherDb... }}
</code></pre>

CC BY-SA 4.0
2018-12-03T23:32:48.673Z
Well, that's fancy!
andrew.welch
CC BY-SA 4.0
2018-12-03T23:30:53.320Z
2018-12-04T01:57:58.463Z
2018-12-04T01:57:58.463Z
Brad Bell
<p>I wrote a free plugin to allow you to do exactly that: <a href="https://github.com/nystudio107/craft-connect" rel="nofollow noreferrer">Connect</a></p>

CC BY-SA 4.0
2018-12-03T23:31:24.247Z
2018-12-03T23:31:24.247Z
andrew.welch
<p>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.</p>

<craft3><database>
Accessing Multiple Databases in Craft
# Accessing Multiple Databases in Craft

(Asked by: username_0 on 2018-12-03)

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.

**Tags:** craft3, database


---

## 2 answers

### Answer by username_1 on 2018-12-03. Score: 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... }}

> **Comments:**
> **username_2**: Well, that's fancy!  

---

### Answer by username_2 on 2018-12-03. Score: 1

I wrote a free plugin to allow you to do exactly that: [Connect](https://github.com/nystudio107/craft-connect)


---

