作者 主題: php下的MVC [Zend Framework] Part 2 資料庫的應用  (閱讀 16259 次)

0 會員 與 1 訪客 正在閱讀本文。

uberr

  • 懷疑的國中生
  • **
  • 文章數: 62
    • 檢視個人資料
    • 天創科技網頁設計公司
今天會教大家如何使用Zend Framework去連接資料庫.Zend_Db提供二種方法去連接資料庫, 1.Zend_Db   ,2. Zend_Db_Table.
今天要介紹的是Zend_Db,是比較簡的一種.Zend_Db所提供的DRBMS有以下:
IBM DB2 (pdo_ibm)
IBM DB2 and Informix Dynamic Server (IDS) (pdo_ibm)
MySQL (pdo_mysql)
MySQLi (mysqli)
Microsoft SQL (pdo_mssql)
Oracle (pdo_oci)
PostgreSQL (pdo_pgsql)
SQLite (pdo_sqlite)

你可以在這裡找到Zend_Db這個class的資料http://framework.zend.com/apidoc/core/


運制流程:
1.建立連接庫的檔案config.ini(host,database,user,password...etc)
2.建立一個連接資料庫的介面
3.開始連接資料庫
4.接收資料,然後回傳到View(頁面)

我們先在application目錄下建立一個config目錄,然後 在config目錄建立config.ini檔案.

config.ini

代碼: [選擇]
[general]
db.adapter = mysqli // 把它改成你的所使用的RDBMS
db.config.host = localhost // 資料庫的位置
db.config.username = username // 連接資料庫的用戶名
db.config.password = password // 連接資料庫的密碼
db.config.dbname = database // 資料庫的名稱

index.php
代碼: [選擇]
<?php

set_include_path
(&#39;.&#39;.PATH_SEPARATOR.&#39;./library/&#39;.PATH_SEPARATOR.&#39;./application/m                                              odels/&#39;); // 設定module的位置
include "Zend/Loader.php"// 必需要include的module,它是把需要的module導入

Zend_Loader::loadClass(&#39;Zend_Controller_Front&#39;); // Zend_Controller_Front是必需的module,它是用來控制route
Zend_Loader::loadClass(&#39;Zend_Db&#39;);
Zend_Loader::loadClass(&#39;Zend_Config_Ini&#39;);
Zend_Loader::loadClass(&#39;Zend_Registry&#39;);

$config = new Zend_Config_Ini(&#39;./application/config/config.ini&#39;,&#39;general&#39;); // 引入資料庫config檔案

// 設定資料庫介面
$dbAdapter Zend_Db::factory($config->db->adapter,$config->db->config->toArray());
Zend_Registry::set(&#39;dbAdapter&#39;,$dbAdapter);

$frontController Zend_Controller_front::getInstance(); // create一個Front Object
$frontController->setControllerDirectory(&#39;./application/controllers&#39;); // 設定Controller目錄的路徑
$frontController->dispatch();

IndexController.php
代碼: [選擇]
<?php

class IndexController extends Zend_Controller_Action
{
    public function 
indexAction()
    {
      try {
        
$db Zend_Registry::get(&#39;dbAdapter&#39;); // 引入資料庫介面
        
$select $db->select();
        
$select->from(&#39;bank&#39;,&#39;*&#39;)  // or (&#39;database&#39;,array(&#39;id&#39;,&#39;username&#39;...etc)
         
->where(&#39;bank_code != ?&#39;,&#39;BBB&#39;)
         
->order(&#39;bank_code&#39;);

        
$result $db->fetchAll($select); // 結果是以Array回傳
        
$this->view->data $result;
      }
      catch(
Zend_Exception $e) {
        echo 
"Error: ".$e->getMessage();
      }
    }
}

index.phtml
代碼: [選擇]
<?php
   
foreach($this->data as $key => $value) :
     echo 
"bankcode=".$value[&#39;bank_code&#39;]." : bank=".$value[&#39;bank&#39;]."<br>";
   
endforeach;
?>


Demo:http://wingning.no-ip.org/studyarea/zend_db/

下載[/color]http://wingning.no-ip.org/studyarea/download/zend_db.tar.gz

天創科技網頁設計公司
« 上次編輯: 2011-10-03 15:09 由 uberr »