How to connect to a database in Magento?

I am trying to create a simple Magento module that needs to be connected to a database at the beginning of every page request. All tables should be available to him. I pull out my hair, trying to figure out how to do it. The best I could understand was that I needed to install this in the config.xml file of my module, but I couldn’t understand exactly what this command was / how it could be used.

Can someone help me or show me how to do this? If not, would it be too bad if a custom config.php file was added that manually connects to the database?

+4
source share
2 answers

Are you trying to use a model or resource object? here is how you can query a table using raw SQL, but you need to know the name of the scoreboard.

 $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 use all models 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 works great for me, hope this answer helps :)

+15
source

What about objects that do not have addAttributeToFilter ? I tried for hours to load a role object by name and nothing works. The only possible method is loading, which will work just fine, if not for the unexplained

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

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

Magento has the Rube Goldberg architecture ...

0
source

All Articles