zend framework配置操作数据库实例分析
后,看了下zend framework配置操作数据库,php教程如下:
在application/configs的文件下建立一个config.ini文件
配置信息如下:
[general]
db.adapter=pdo_mysql
db.config.host=localhost/iparess
db.config.username=username
db.config.password=password
db.config.dbname=databasename
2、
在pulibc 目录的index.php页面中
/** zend_application */
require_once 'zend/application.php';
的下面插入
//set the datase config
require_once 'zend/config/ini.php';
require_once 'zend/registry.php';
require_once 'zend/db.php';
require_once 'zend/db/table.php';
$config=new zend_config_ini('./../application/configs/config.ini',null, true);
zend_registry::set('config',$config);
$dbadapter=zend_db::factory($config->general->db->adapter,$config->general->db->config->toarray());
$dbadapter->query('set names utf8');
zend_db_table::setdefaultadapter($dbadapter);
zend_registry::set('dbadapter',$dbadapter);
就此,我就用我的本地wordpress数据库来测试下,就用wp_posts表来测试吧:
首先模型models建立wp_posts.php
<?php
class wp_posts extends zend_db_table{
protected $_name = 'wp_posts';
protected $_primary = 'id';
}
?>
控制器controller下面建立indexcontroller.php
<?php
require_once application_path.'/models/wp_posts.php';
class indexcontroller extends zend_controller_action
{
public function init()
{
/* initialize action controller here */
}
public function indexaction()
{
$con = new wp_posts();
$res = $con->fetchall()->toarray();
$this->view->res = $res;
$this->render("index");
}
}
在views/scripts/index/ 建立视图:index.phtml
<html>
<head>
<title>this is for test</title>
</head>
<body>
<table>
<?php foreach ($this->res as $news){?>
<tr>
<td><?php echo $news['id']?></td>
<td><?php echo $news['post_title']?></td>
<td><?php echo $news['post_date']?> </td>
</tr>
<?php }?>
</table>
</body>
</html>
ok啦,浏览器显示: