How to create new databse connections in magento

A resource in Magento is used to manage database connections. Resources are defined under the global XML tag of any config.xml file. To make a new database connection, we have to add an XML file, such as the app/etc/config.xml file. Each resource has a name. Connection names are generally of the pattern module_read, module_write, or module_setup. In this recipe, we will play with the resource and create a new database connection, which would work on any database that we specify.
  • We will print the data in the product view page for development purpose. Let us open the view.phtml file from app/design/frontend/YOUR_INTERFACE/YOUR_THEME/template/catalog/product/ folder.
  • Append the following code snippet at the top of view.phtml: '; var_export($singleton->debug()); echo '
'; ?>
  • Visit any product details page to see the results in your browser.
  • getConnection('core_read'); $results = $conn->query('SELECT * FROM admin_user')->fetchAll(); echo '
    ';
       var_export($results);
       echo '
    '; ?>
  • Run this code by visiting any product details page. You should see a page similar to this:

  • 'localhost', 'username' => 'root', 'password' => 'pass', 'dbname' => 'ess' ); $_resource = Mage::getSingleton('core/resource'); $_conn = $_resource->createConnection('customConnection','pdo_mysql', $conf); $results = $_conn->query('SELECT * FROM wp_posts')->fetchAll(); echo '
    ';
      print_r($results);
      echo '
    '; ?>
  • This way we can connect an external database and run the query using Magento’s resource. We have connected an external WordPress database and fetched the wp_posts table. To see it in action, visit a product details page.
  • Here is another filter for SKU: getCollection(); echo "Our collection now has " . count($collection_of_products) .' item(s)'; $collection_of_products->addFieldToFilter('sku', 'mycomputer'); echo '
    ';
       var_export($collection_of_products->getFirstItem()->getData());
       echo '
    '; ?>
  • Post a Comment

    Previous Post Next Post