Connect to Magento DB externally via Singleton/Resource Model

Submitted by deeperdata - 3 years ago

This method can be used to create external forms that access Magento, run maintenance queries, anything that requires database access. The first 3 lines pull the MySQL DB credentials for whichever install you specify.

<?php

require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();

// Now you can run ANY Magento code you want

    /**
     * Get the resource model
     */
    $resource = Mage::getSingleton('core/resource');

    /**
     * Retrieve the read connection
     */
    $readConnection = $resource->getConnection('core_read');
     
    /**
     * Retrieve the write connection
     */
     $writeConnection = $resource->getConnection('core_write');

    /**
     * Example 1: Assemble select query as PHP variable $selectquery
     */
    
    $selectquery = 'select * from salesrule_coupon where times_used="20";';

    /**
     * Execute the query and store the results in $results array
     */
     $results = $readConnection->fetchAll($selectquery);
     
    /**
     * Example 2: Assemble update query as PHP variable $updatequery
     */
    
    $updatequery = 'update salesrule_coupon SET times_used="0" where times_used="20";';

    /**
     * Execute the update query
     */
     
     $writeConnection->query($updatequery);
     
affiliate_link
Learn PHP
comments powered by Disqus
Proudly hosted on Digital Ocean