Create An External Database Connection in Magento

Posted on March 29, 2010 by BT There have been 16 comment(s)

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.

<?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:

<?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

<?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

<?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

<?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.

<?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.

<?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 Magento Tutorials and was tagged with Magento Advanced, Magento Tips

16 Responses to Create An External Database Connection in Magento

  • aannemarie

    great, worked instantly :)

    thank you

    Posted on June 29, 2010 at 6:37 pm

  • PJ
    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

  • Richard Gere

    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

  • fishpig
    fishpig says:

    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

  • fishpig
    fishpig says:

    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

  • Alan Henrique

    Tks bro. This article it's very good.

    Posted on September 3, 2010 at 7:31 pm

  • Vignesh Sabapathi

    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

  • Mukesh
    Mukesh says:

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

    Posted on January 7, 2011 at 6:26 am

  • Mukesh
    Mukesh says:

    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
    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

  • haltabush

    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
    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.

    Posted on May 10, 2011 at 11:38 am

  • Ed
    Ed says:

    What we would like to do with this is connect to our live ERP database to pull inventory amounts for the in stock or out of stock on the products and to pull pricing from the same database. Would this work for that?

    Posted on May 20, 2011 at 3:52 pm

  • Magento One Step Checkout

    Hello Thanx man, this post has bee most helpful for me to understand the database connection in magento. You rock man. many Thanks.

    Posted on September 2, 2011 at 1:45 pm

  • RITI
    RITI says:

    Hi,

    Minor rectification -
    Mage_Core_Model_Mysq4_Collection_Abstract instead of
    Mage_Core_Model_Mysql4_Collection_Abstract in Collection.php

    Thanks
    Riti

    Posted on December 7, 2011 at 9:58 am

  • Riti
    Riti says:

    Hi,

    Thanks for tutorial.
    I tried and it is working fine in community version but in Enterprise edition 1.10.1.1
    Mage::getModel('externaldb/book')->getCollection() is not returning anything. not even error.

    Is there any way to make it work for enterprise as well?

    Posted on December 8, 2011 at 9:19 am

16 Item(s)

Have your say...

You must be logged in to post a comment.