Zend Framework连接MySQL数据库配置与实现
本例详细解析利用Zend Framework建立MySQL数据库连接的操作流程,供读者参考借鉴。
执行前需确认系统已正确加载PDO扩展,具体操作为修改php.ini配置文件。
extension=php_pdo.dll
extension=php_pdo_mysql.dll
在配置文件中手动添加以下两行代码(确保行首无分号注释符号):
同时需调整extension_dir参数
extension_dir = "C:/php5/ext"
使其指向包含php_pdo.dll及php_pdo_mysql.dll的目录,例如:
配置完成后即可开始后续开发。
<?php
//...省略
$params = array ('host' => '127.0.0.1',
'username' => 'root',
'password' => '123456',
'dbname' => 'happycms');
$db = Zend_Db::factory('pdoMysql', $params);
Zend::register('db', $db);
?>
index.php作为网站唯一入口文件。
<?php
class App_Article {
private $db;
function App_Article() {
$this->db = Zend::registry('db');
}
function listAll() {
$result = $this->db->query('SELECT * FROM article');
$rows = $result->fetchAll();
Zend::dump($rows);
}
function listByCategory() {
}
//...省略
}
?>
lib/App/Article.php用于定义文章业务逻辑。
class articleController extends Zend_Controller_Action {
private $view;
private $article;
function __c****truct() {
$this->view = Zend::registry('view');
$this->article = new App_Article();
}
public function listAllAction() {
$this->article->listAll();
$this->view->title='View Articles';
echo $this->view->render(TPL_DIR.'/tplView.php');
}
function __call($action, $arguments)
{
$this->_redirect('./');
print_r($action);
print_r($arguments);
}
}
?>
ArticleController.php负责处理控制器逻辑。
浏览器访问 http://happycms/article/listall 可触发列表功能。
array(1) {
[0] => array(15) {
["articleid"] => string(1) "1"
["categoryid"] => string(1) "0"
["articletitle"] => string(4) "test"
["articlefromwhere"] => string(3) "sdf"
["articlekeywords"] => string(5) "sdfds"
["articledescription"] => string(4) "test"
["articlebody"] => string(9) "sffsdfsdf"
["authorname"] => string(8) "haohappy"
["authoremail"] => string(11) "s...@df.com"
["issticky"] => string(1) "0"
["isrecommanded"] => string(1) "0"
["includeattachment"] => string(1) "0"
["addtime"] => string(19) "0000-00-00 00:00:00"
["lastedittime"] => string(19) "0000-00-00 00:00:00"
["checktime"] => string(19) "0000-00-00 00:00:00"
}
页面将返回如下数据结构输出: