今天会教大家如何使用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;
?>
ZF 资料库的使用
最新推荐文章于 2024-07-25 11:35:55 发布