1、配置文件配置數據庫選項,application/configs/application.ini中添加
[mysql]
db.adapter = PDO_MYSQL
db.params.host = localhost #數據庫服務器名稱
db.params.username = root #數據庫用戶名
db.params.password = **** #數據庫密碼
db.params.dbname = news #數據庫名字
2、在application/Bootstrap.php中添加構造函數
function __construct($app){
parent::__construct($app);
//初始化數據庫適配器
$url = constant("APPLICATION_PATH").DIRECTORY_SEPARATOR.'/configs/application.ini';
$dbconfig = new Zend_Config_Ini($url , "mysql");
$db = Zend_Db::factory( $dbconfig->db);
$db->query('set names utf8');
Zend_Db_Table::setDefaultAdapter($db);
}
3、在application/models下建立model文件
如:User.php
<?php
class User extends Zend_Db_Table{
protected $_name='user'; //數據表名
protected $_parimary='uid'; //數據表主鍵
}
4、在application/controllers/IndexController.php(控制器任意)寫代碼,
如:
require_once APPLICATION_PATH.'/models/User.php'; //引入model文件
class IndexController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
$m = new User(); //實例化model
$res = $m->fetchAll()->toArray(); //全表查詢並轉換成數組數據
$this->view->res = $res; //傳送數據到index.phtml 模板
}
}
5、在views/scripts/index/index.phtml中使用原生php輸出數據,如
<?php
foreach ($this->res as $v) {
# code...
echo "uid: ".$v['uid']."----username: ".$v['username']."<br/>";
}
?>
6、再訪問http://www.hunhun.com/index/index,則會看到數據表user表的數據輸出