今天會教大家如何使用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('.'.PATH_SEPARATOR.'./library/'.PATH_SEPARATOR.'./application/m odels/'); // 設定module的位置
include "Zend/Loader.php"; // 必需要include的module,它是把需要的module導入
Zend_Loader::loadClass('Zend_Controller_Front'); // Zend_Controller_Front是必需的module,它是用來控制route
Zend_Loader::loadClass('Zend_Db');
Zend_Loader::loadClass('Zend_Config_Ini');
Zend_Loader::loadClass('Zend_Registry');
$config = new Zend_Config_Ini('./application/config/config.ini','general'); // 引入資料庫config檔案
// 設定資料庫介面
$dbAdapter = Zend_Db::factory($config->db->adapter,$config->db->config->toArray());
Zend_Registry::set('dbAdapter',$dbAdapter);
$frontController = Zend_Controller_front::getInstance(); // create一個Front Object
$frontController->setControllerDirectory('./application/controllers'); // 設定Controller目錄的路徑
$frontController->dispatch();
IndexController.php<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
try {
$db = Zend_Registry::get('dbAdapter'); // 引入資料庫介面
$select = $db->select();
$select->from('bank','*') // or ('database',array('id','username'...etc)
->where('bank_code != ?','BBB')
->order('bank_code');
$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['bank_code']." : bank=".$value['bank']."<br>";
endforeach;
?>
Demo:http://wingning.no-ip.org/studyarea/zend_db/下載[/color]
http://wingning.no-ip.org/studyarea/download/zend_db.tar.gz天創科技網頁設計公司