Create An External Database Connection in Magento

piaoling  2011-06-23 19:01:13
While I'm confident that many people in the Magenosphere have figured this one out, it took a whole Saturday night and part of my soul for me to achieve it. Hopefully, by presenting this code here, I can save you from the pain I endured :)

Creating The Connection

To create your connection, create a custom module and add the following to your config.xml. The code below is the bare minimum needed to get the external database connection working.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?xml version=”1.0″?>
<config>
    <modules>
        <Fishpig_Externaldb>
            <version>0.1.0</version>
        </Fishpig_Externaldb>
    </modules>
    <global>
        <resources>
            <externaldb_write>
                <connection>
                    <use>externaldb_database</use>
                </connection>
            </externaldb_write>
            <externaldb_read>
                <connection>
                    <use>externaldb_database</use>
                </connection>
            </externaldb_read>
            <externaldb_setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </externaldb_setup>
            <externaldb_database>
                <connection>
                    <host><![CDATA[localhost]]></host>
                    <username><![CDATA[db_username]]></username>
                    <password><![CDATA[db_password]]></password>
                    <dbname><![CDATA[db_name]]></dbname>
                    <model>mysql4</model>
                    <type>pdo_mysql</type>
                    <active>1</active>
                </connection>
            </externaldb_database>
        </resources>
    </global>
</config>
Clear the cache after creating your module and from now on, each time you load Magento, a second database connection will be created

Accessing The Database

When I initially found out how to create an external database connection, I was using Zend_Db to retrieve all of my information. You can use the following to test your database connection is working:
?
1
2
3
4
5
6
7
<?php
 
    $resource   = Mage::getSingleton(‘core/resource’);
    $conn       = $resource->getConnection(‘externaldb_read’);
    $results    = $conn->query(‘SELECT * FROM tblName’);
    
    print_r($results)
This works fine, however kind of takes the point away from having this connection available in Magento.

Accessing The External Database Using Models

Using models to access the database keeps our code style uniform throughout Magento. Also, it means we can integrate any other CMS or database driven application without learning it's coding practices. To achieve this, simply add models to your custom module like you would for any other module. I will attempt to demonstrate how to set up the models and config.xml files now. For this example I will pretend I am integrating Magento with a system that lists books (reading is cool!).

Creating The Model Class Files

Create the following files:

code/local/Fishpig/Externaldb/Model/Book.php

?
1
2
3
4
5
6
7
8
9
<?php
 
class Fishpig_Externaldb_Model_Book extends Mage_Core_Model_Abstract
{
    public function _construct()
    {
        $this->_init('externaldb/book');
    }
}

code/local/Fishpig/Externaldb/Model/Mysql4/Book.php

?
1
2
3
4
5
6
7
8
9
<?php
 
class Fishpig_Externaldb_Model_Mysql4_Book extends Mage_Core_Model_Mysql4_Abstract
{
    public function _construct()
    {
        $this->_init('externaldb/book', 'book_id'); // book_id refers to the primary key of the book table
    }
}

code/local/Fishpig/Externaldb/Model/Mysql4/Book/Collection.php

?
1
2
3
4
5
6
7
8
9
<?php
 
class Fishpig_Externaldb_Model_Mysql4_Book_Collection extends Mage_Core_Model_Mysq4_Collection_Abstract
{
    public function _construct()
    {
        $this->_init('externaldb/book');
    }
}
That's the bare minimum needed for your models to be able to access the database!

Adding the Models to The Config

To inform Magento about our models, we need to register them in config.xml. Below is an updated version of config.xml with the models for Book registered.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?xml version=”1.0″?>
<config>
    <modules>
        <Fishpig_Externaldb>
            <version>0.1.0</version>
        </Fishpig_Externaldb>
    </modules>
    <global>
        <models>
            <externaldb>
                <class>Fishpig_Externaldb_Model</class>
                <resourceModel>externaldb_mysql4</resourceModel>
            </externaldb>
            <externaldb_mysql4>
                <class>Fishpig_Externaldb_Model_Mysql4</class>
                <entities>
                    <book>
                        <table>library_book</table>
                    </book>
                </entities>
            </externaldb_mysql4>
        </models>
        <resources>
            <externaldb_write>
                <connection>
                    <use>externaldb_database</use>
                </connection>
            </externaldb_write>
            <externaldb_read>
                <connection>
                    <use>externaldb_database</use>
                </connection>
            </externaldb_read>
            <externaldb_setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </externaldb_setup>
            <externaldb_database>
                <connection>
                    <host><![CDATA[localhost]]></host>
                    <username><![CDATA[db_username]]></username>
                    <password><![CDATA[db_password]]></password>
                    <dbname><![CDATA[db_name]]></dbname>
                    <model>mysql4</model>
                    <type>pdo_mysql</type>
                    <active>1</active>
                </connection>
            </externaldb_database>
        </resources>
    </global>
</config>

That's it, the models should now be registered in Magento!

Testing The Models

Testing them is easy enough, just treat them like normal Magento models.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
    
    // Load the book with a primary key value of 4
    $_book = Mage::getModel('externaldb/book')->load(4);
 
    // This would print out the value in the field isbn in the external database
    echo $_book->getIsbn();
 
    //You can even update records!
    $_book->setName('1984');
    $_book->setAuthor('George Orwell');
 
    try {
      $_book->save();
    } catch (Exception $e) {
      exit($e->getMessage());
    }
   

Conclusion

This is one of my first blogs so I probably haven't written this up as well as I could have, however, I think that using a second database in Magento can be extremely useful. I've written a very good Wordpress/Magento plugin which gives access to all Wordpress post/category/image/link etc information. If you would like to discuss this plugin or would like to use it in one of your sites then please let me know!

This post was posted in General

16 Responses to Create An External Database Connection in Magento

  • great, worked instantly :)

    thank you

    Posted on June 29, 2010 at 6:37 pm

  • PJ says:

    I've done this twice, from scratch but it keeps trying to get the table from the magento datbase:
    SQLSTATE[42S02]: Base table or view not found: 1146 Table 'magento.tbl_class' doesn't exist"

    Posted on July 22, 2010 at 8:29 am

  • I want to get the connection values in a php page. Is it possible to have username, password and databasename accessed in a php page at root level.

    Posted on July 30, 2010 at 11:37 am

  • You need to map your table name to your external database. I don't have the code on me at the top moment but will publish it as soon as I have access to my computer (I'm on my laptop currently).

    Posted on July 31, 2010 at 8:05 am

  • I'm not entirely sure what you mean.

    Are you saying you want to be able to access your Magento database connection details outside of Magento?

    Posted on July 31, 2010 at 8:13 am

  • Tks bro. This article it's very good.

    Posted on September 3, 2010 at 7:31 pm

  • great tutorial..Very helpful in creating an external db connection. Instantly worked. Thanks a lot and nice work... Keep blogging

    Posted on December 22, 2010 at 9:35 am

  • Very helpful tutorial. Thanks for it. Keep posting...

    Posted on January 7, 2011 at 6:26 am

  • ops.. I am also having the same problem as that of @PJ :

    SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘magento.tbl_class’ doesn’t exist”

    @fishpig: Can you add more detail on how to map table name to external database?

    Posted on January 7, 2011 at 10:29 am

  • Mehdi says:

    Hi!
    I would like to create an external database on magento where I'll put all users information. Make magento write on it every time a user change something in there profiles, disable newsletter...
    For now, I'm juste trying to extract data from the magento database, put it all together in one or two tables, and updat it myself from time to time.
    This external database will be used by company which handles the CRM..

    Any Ideas ??
    Thank you by the way for the tutorial!

    Posted on January 12, 2011 at 11:56 am

  • Hi there,
    I'd like to use your tutorial for an import facility (basically, connect to osCommerce db, grab customer data & save it in Magento)
    Do to that, I'll probably need to have 2 kinds of models : one fetching data from the oscommerce database, and an other one using Magento default db. Do you know any way to achieve that? Thx :)

    Posted on February 15, 2011 at 10:09 am

  • dice says:

    Nice article..........
    But I am still confuse.
    Plese explain me where i need to upload config file or use default one app/code/etc?
    From where I can check database connection?
    From where I write a query for external database ?
    Please tell me in detaile .I follow above step as it is but still .............
    Please any one help me out tell me in detaile.

类别 :  magento(258)  |  浏览(6290)  |  评论(0)
发表评论(评论将通过邮件发给作者):

Email: