Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7580311
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T17:53:08+00:00 2026-05-30T17:53:08+00:00

I am working on a magento admin module and currently I am running a

  • 0

I am working on a magento admin module and currently I am running a database query in a sloppy fashion, by directly loading a php file and connecting with a php file outside of the module:

<?php 
header("Content-type: text/xml");
$host           = "localhost";
$user           = "root";
$pw             = "foo";
$database       = "db";
$link           = mysql_connect($host,$user,$pw) or die ("Could not connect.");
$db_selected = mysql_select_db($database, $link); if (!$db_selected) {
    die ('Can\'t use ' . $database . ' : ' . mysql_error()); }


// connect to database
$link   = mysql_connect($host . ":" . $port,$user,$pw) or die ("Could not connect.");

// Select DB
$db_selected = mysql_select_db($database, $link); if (!$db_selected) {
    die ('Can\'t use ' . $database . ' : ' . mysql_error()); }

// Database query
$query = ("SELECT cpsl.parent_id AS 'foo'
  , cpe.type_id AS 'bar'
  , LEFT(cpe.sku, 10) AS 'color'
  ....
GROUP BY 1,2,3,4,5,6,7,8,9
ORDER BY 1,2,3,4,5,6,7,8,9
;");

// Execute query
$result = mysql_query($query, $link) or die("Could not complete database query");

// Populate array
while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray));

  $doc = new DOMDocument();
  $doc->formatOutput = true;

  $r = $doc->createElement( "DATA" );
  $doc->appendChild( $r );

  foreach( $resultArray as $product )
  {
  $b = $doc->createElement( "ITEM" );

  // MagentoID
  $magento_id = $doc->createElement( "MAGENTO_ID" );
  $magento_id->appendChild(
  $doc->createTextNode( $product['MagentoID'] )
  );
  $b->appendChild( $magento_id );
....

 }

// Save XML
  echo $doc->saveXML();

// Close connection
mysql_close($link);

?>

Can someone please explain a better way to write this into the module? I know I can make the connection much easier (more secure?) using magentos methods. Can I put this whole query directly in the controller for the module? Something like this? :

public function queryAction()
    {
$readConnection = $resource->getConnection('core_read');
$query = ("SELECT cpsl.parent_id AS 'foo'
...
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T17:53:10+00:00Added an answer on May 30, 2026 at 5:53 pm

    Yes, you can do what you propose.

    I have something like the following:

    class Foo {
        protected $db;
    
        public function _construct() {
            /* Change core_write to core_read if you're just reading */
            $this->db = Mage::getSingleton('core/resource')->getConnection('core_write');
        }
    
        private function doAQuery() {
            $sql = "SELECT * FROM foobar f;";
            $data = $this->db->fetchAll($sql);
            /* do something with the data here */
        }
    
        private function doAQueryADifferentWay() {
            $sql = $this->db->select();
            $sql->from(array('f' => 'foobar'));
            $data = $this->db->fetchAll($sql);
            /* do something with the data */
        }
    }
    

    edited to add

    You can make the call directly from the controller by defining the methods in the controller and calling them with something like $this->doAQuery(); I’m a pretty big fan of putting things in the right place for easier maintainability, though, so I’ll outline the steps needed to do that.

    I’m going to assume you know how to/can read the docs on how to create a skeleton module, but I may end up talking down a bit. Apologies in advance.

    For the sake of argument, I’m going to call our example module Zac_Example. So we’ll pretend we have a module in app/code/local/Zac/Example. Any further paths will assume we’re starting in that directory.

    First, you need to define a model (I guess you could use a helper if you prefer) and controller, so we define those in etc/config.xml

    ...
      <frontend>
        <routers>
          <zac_example>
            <use>standard</use>
            <args>
              <module>Zac_Example</module>
              <!-- Mind the capital N, it gets me every time -->
              <frontName>example</frontName>
            </args>
          </zac_example>
        </routers>
      </frontend>
      <global>
        <models>
          <zac_example>
            <class>Zac_Example_Model</class>
          </zac_example>
        </models>
      </global>
    ...
    

    Now we define our model in Model/Query.php, which is Foo from above, but using the Magento naming convention:

    class Zac_Example_Model_Query extends Mage_Core_Model_Abstract {
        protected $db;
    
        /* you don't have to do this, as you can get the singleton later if you prefer */
        public function __construct() {
            $this->db = Mage::getSingleton('core/resource')->getConnection('core_write');
        }
    
        public function doAQuery() {
            /* If you chose not to do this with the constructor:
             * $db = Mage::getSingleton('core/resource')->getConnection('core_write');
             */
    
            $sql = "SELECT * FROM foobar f;";
            /* or $db->fetchAll($sql); */
            $this->db-fetchAll($sql);
            /* do something with the data here */
            return $response
        }
    
        public function doAQueryADifferentWay($somerequestdata) {
            $sql = $this->db->select();
            $sql->from(array('f' => 'foobar'));
            $sql->where('f.somedata', array('eq' => $somerequestdata));
    
            $data = $this->db->fetchAll($sql);
            /* do something with the data */
        }
    }
    

    Now, having a model, we can set up a controller. We’ll call the controller test, so the following goes in controllers/TestController.php. The actions, we’ll call foo and bar.

    class Zac_Example_TestController extends Mage_Core_Controller_Front_Action {
    
        public function fooAction() {
            $model = Mage::getModel('zac_example/query');
            $result = $model->doAQuery();
            $this->getResponse()->setBody(Zend_Json::encode($result));
            $this->getResponse()->sendResponse();
            exit; // We're done, right?
        }
    
        /* This assumes the request has a post variable called 'whatever' */
        public function barAction() {
            $model = Mage::getModel('zac_example/query');
            $param = $this->getRequest()->getParam('whatever');
            $result = $model->doAQueryADifferentWay($param);
            $this->getResponse()->setBody(Zend_Json::encode($result));
            $this->getResponse()->sendResponse();
            exit; // We're done, right?
        }
    

    Given that particular set of facts, the URLs in question would be http://yourserver/example/test/foo and http://yourserver/example/test/bar. If we had named the controller file IndexController.php, they would be http://yourserver/example/index/foo and http://yourserver/example/index/bar.

    If you only have one action you need to make available, you can name the controller file IndexController.php and the method in the controller indexAction and use the URL http://yourserver/example/.

    I’m shooting from the hip, so don’t be surprised if there’s at least one braino or typo somewhere.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am working on a custom module in magento admin that uses the ‘sales/order_grid_collection’
I am currently working on a Magento extension, and I have overridden a core
I'm currently working on a new Magento template, and I'm facing problems with jQuery.
I am working on a new payment module for Magento and have come across
I am currently working on a Magento store (ver. 1.6.2.0) however when i click
I am working in a new Filter by Product module in Magento, i have
I am working on a Magento module that has a Form where a user
Im currently working on a custom product list in the Magento backend. Heres the
I'm looking for a working example of a Magento API-enabled module. How can I
I am currently working on an integration between a .Net app and Magento v

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.