How to connect to the database in Magento?


I'm trying to build a simple Magento Module that needs to connect to the database at the start of each page request. All tables need to be accessible to it. I've been pulling my hair out trying to understand how to do it. The best I could figure out was that I need to set this in the config.xml file of my module, but exactly what that command is/how it may be used, i haven't been able to figure out.

Can someone please guide me or show me how to accomplish this? If not, would it be too bad a practice to include a custom config.php file which connects to the database manually?

4/25/2009 4:23:04 AM

Accepted Answer

Are you trying to use a resource model or entity ? here is how you can query a table using raw SQL but you need to know the tablename.

$w = Mage::getSingleton('core/resource')->getConnection('core_write');
$result = $w->query('select entity_id from catalog_product_entity');

if (!$result) {
    return false;

$row = $result->fetch(PDO::FETCH_ASSOC);
if (!$row) {
    return false;

When trying to all a model you can use

$products = Mage::getModel('catalog/product')->getCollection();

$products->addAttributeToFilter('entity_id', array('in' => array(1,2)));


foreach ($products as $_prod) {

I use the second method for my custom modules and it has worked out fine for me , hope this answer helps :)

4/28/2014 9:01:08 AM

What about objects that do not have addAttributeToFilter? I've been trying for hours to load a role object by its name and nothing works. The only possible method is load, which would work perfectly if not for an unexplicable

if (!intval($value) && is_string($value)) {
   $field = 'role_id';

in Mage_Admin_Model_Mysql4_Role::load, which only makes it impossible to filter using a string value.

Magento has a Rube Goldberg architecture...

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow