2011-08-02 112 views
3

我想知道Magento是否可以连接到它的主数据库,以及另一个不包含Magento核心信息的数据库?Magento可以连接到另一个MySQL数据库吗?

例如,我希望能够从存储在不同服务器上不同数据库上的WordPress安装中查询表格?

我的第一本能是使用mysql_connect创建一个新的数据库连接,但是这样做并不合适。

有没有更“适当”的方法来完成这个?

回答

9

这里完整的解释:在短http://fishpig.co.uk/magento-tutorials/create-an-external-database-connection-in-magento
,你需要创建一个新的资源,并告诉Magento的利用这个资源,你的模型,即在config.xml,里面<global>标签:

<resources> 
     <external_db> 
      <connection> 
       <host><![CDATA[host]]></host> 
       <username><![CDATA[username]]></username> 
       <password><![CDATA[password]]></password> 
       <dbname><![CDATA[dbname]]></dbname> 
       <model>mysql4</model> 
       <type>pdo_mysql</type> 
       <active>1</active> 
      </connection> 
     </external_db> 
     <yourmodelalias_read> 
      <connection> 
       <use>external_db</use> 
      </connection> 
     </yourmodelalias_read> 
    </resources> 
+0

是这是最好的答案。如果您使用vcs并具有开发工具,舞台和生产服务器,那么您可能需要将标记扔到local.xml中,而不是模块的config.xml。这样你的各种系统可以配置不同的用户/密码。那么我想我假设你的local.xml不在你的vcs中,而是你手动管理它。 – shaune

1

如果您在/lib/Varien/Db/Adapter/Mysqli.php看你可以看到,Magento的是扩展Zend_Db_Adapter_Mysqli,并在该连接的缓存副本立即存在,它正在检查_connect()函数。

对我来说,似乎不太可能直接使用Magento Db适配器,因为您必须重写此功能。所以,这留下了两个选择:

  1. 使用Zend DB适配器,如果您以前使用过,它非常容易。
  2. 直接使用PHP的MySQL函数。确保使用PDO或MySQLi库,而不是ext/mysql。 ext/mysql库已经被弃用,并且很难安全使用。

http://php.net/manual/en/ref.pdo-mysql.php

http://php.net/manual/en/book.mysqli.php

http://framework.zend.com/manual/en/zend.db.html

编辑:添加Magento的连接模块

http://www.magentocommerce.com/magento-connect/fishpig/extension/3958/fishpig_wordpress_integration

即一个自由Magento-> WordPress的桥。可能值得看看他们的来源,看看他们采取了什么样的道路。

0

在你的模块等/ config.xml中添加以下代码:

<global> 
    <resources> 
     <modulename_write> 
      <connection> 
       <use>modulename_database</use> 
      </connection> 
     </modulename_write> 
     <modulename_read> 
      <connection> 
       <use>modulename_database</use> 
      </connection> 
     </modulename_read> 
     <modulename_setup> 
      <connection> 
       <use>core_setup</use> 
      </connection> 
     </modulename_setup> 
     <modulename_database> 
      <connection> 
       <host><![CDATA[localhost]]></host> 
       <username><![CDATA[db_username]]></username> 
       <password><![CDATA[db_password]]></password> 
       <dbname><![CDATA[tablename]]></dbname> 
       <model>mysql4</model> 
       <type>pdo_mysql</type> 
       <active>1</active> 
      </connection> 
     </modulename_database> 
    </resources> 
</global> 

要使用新表中获取数据数据库:

<?php 
    $resource = Mage::getSingleton('core/resource'); 
    $conn  = $resource->getConnection('modulename_read'); 
    $results = $conn->fetchAll('SELECT * FROM tablename'); 

    echo "<pre>"; 
    print_r($results); 
?> 
相关问题