我正在研究一個magento管理模塊,目前我正在通過直接加載一個php文件並在模塊外部連接一個php文件來以馬虎的方式運行數據庫查詢:直接從控制器運行SQL查詢
<?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);
?>
有人可以請解釋一個更好的方式來寫入模塊?我知道我可以使用magentos方法使連接更容易(更安全?)。我可以將整個查詢直接放在模塊的控制器中嗎?像這樣? :
public function queryAction()
{
$readConnection = $resource->getConnection('core_read');
$query = ("SELECT cpsl.parent_id AS 'foo'
...
}
在你的「Populate array」行中,它看起來像'$ resultArray'應該是空的,因爲每個記錄都被彈出。這實際上工作嗎? – clockworkgeek 2012-03-01 20:05:42
它確實有效。我只是想將它從這個php文件移動到magento中。我從維爾多斯的回答中看到,我正處在正確的軌道上,但是我仍然不明白我是如何在控制器中調用它的。 – Zac 2012-03-02 01:02:36