簡體   English   中英

如何在Zend Framework中配置和訪問MySQL數據庫?

[英]How to config and access MySQL database in Zend Framework?

我是Zend Framework的新手。

我嘗試通過以下方式訪問MySQL數據庫

    $db = new Zend_Db_Adapter_Pdo_Mysql(
        [
            'host' => 'localhost',
            'username' => 'user',
            'password' => 'pass',
            'dbname' => 'database'
        ]
    );
    $query = 'SELECT * FROM table_name';
    $this->view->rec = $this->db->fetchAll($query);

在每個控制器上訪問數據庫都很好。 (我想要單配置。)

所以,我嘗試通過Bootstrap配置,

   $this->bootstrap('db');
    switch (APPLICATION_ENV) {

        case 'development' :
            // this allows you to profile your queries through the firebug console
            $profiler = new Zend_Db_Profiler_Firebug('System Queries');
            $profiler->setEnabled(true);
            $this->getPluginResource('db')->getDbAdapter()->setProfiler($profiler);
            break;

        case 'production' :
            // if you use meta caching in production, which you should :)
            // Zend_Db_Table_Abstract::setDefaultMetadataCache($this->_cache);
            break;
    }

如何訪問此實例以從“ ”中檢索數據?

還是有其他解決方案?

提前致謝 !

嘗試通過Adapter Factory設置默認適配器

$db = Zend_Db::factory('Pdo_Mysql', array(
'host'     => BASEHOST,
'username' => BASEUSR,
'password' => BASEPASS,
'dbname'   => BASE
));
Zend_Db_Table::setDefaultAdapter($db);

現在您可以為表格建立模型

<?php
class YourTable extends Zend_Db_Table_Abstract{
  protected $_name = 'table' //your table;
}

最終獲取數據

<?php
$model = new YourTable();
$this->view->red = $model->fetchAll();

這種方法的優勢在於,您現在可以取消查詢的耦合,並且可以在模型上集成自定義邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM