Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect to the database in Magento?

Tags:

php

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?

like image 948
Ali Avatar asked Apr 25 '09 04:04

Ali


People also ask

Where is Magento database?

To get DB config file go to:/<Magento Install Dir>/app/etc/local. xml; having accessed Magento database config file location, edit local.

How does Magento 2 database work?

How does Connection to Database Works in Magento 2? In Magento 2, database connection settings are contained in the app/etc/env. php file: The path to this file is stored in \Magento\Framework\Config\File\ConfigFilePool class in a private array $applicationConfigFiles.


1 Answers

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

$products->addAttributeToSelect('*');
$products->load();

foreach ($products as $_prod) {
   var_dump($_prod->getData());
}

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

like image 135
Rick J Avatar answered Oct 06 '22 02:10

Rick J