首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Zend Framework 1.x Zend_Db 連線 MySQL 完整實戰教學

     編輯:PHP 相關知識

前置需求:啟用 PDO 擴展

Zend_Db 底層依賴 PDO,必須在 php.ini 啟用:

extension=php_pdo.dll
extension=php_pdo_mysql.dll
extension_dir = "C:/php5/ext"  ; 指向 DLL 實際目錄

重啟 Apache/IIS 後,phpinfo() 應顯示 PDO drivers: mysql。

核心架構:單一入口 + 註冊表模式

ZF1 採用 Front Controller 模式,index.php 為唯一入口,建立資料庫連線並存入 Zend_Registry 供全域存取。

1. 入口文件:建立連線並註冊

<?php
// index.php
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance()->setFallbackAutoloader(true);

// 資料庫連線參數
$params = [
    'host'     => '127.0.0.1',
    'username' => 'root',
    'password' => '123456',
    'dbname'   => 'happycms',
    'charset'  => 'utf8',           // 重要:設定連線字符集
    'driver_options' => [
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
    ]
];

// 工廠方法建立適配器
$db = Zend_Db::factory('Pdo_Mysql', $params);

// 存入註冊表,鍵名 'db'
Zend_Registry::set('db', $db);

// 啟動前端控制器
$front = Zend_Controller_Front::getInstance();
$front->setControllerDirectory('./application/controllers');
$front->dispatch();
?>

2. 模型層:從註冊表取得連線

<?php
// application/models/Article.php
class App_Article {
    private Zend_Db_Adapter_Abstract $db;

    public function __construct() {
        $this->db = Zend_Registry::get('db');
    }

    public function listAll(): array {
        // 直接查詢並返回陣列
        return $this->db->fetchAll('SELECT * FROM article');
    }

    public function listByCategory(int $categoryId): array {
        // 參數綁定防注入
        return $this->db->fetchAll(
            'SELECT * FROM article WHERE category_id = ? ORDER BY addtime DESC',
            [$categoryId]
        );
    }

    public function getById(int $id): ?array {
        return $this->db->fetchRow('SELECT * FROM article WHERE articleid = ?', [$id]);
    }
}
?>

3. 控制器層:協調模型與視圖

<?php
// application/controllers/ArticleController.php
class ArticleController extends Zend_Controller_Action {
    private App_Article $article;
    private Zend_View_Interface $view;

    public function init() {
        $this->article = new App_Article();
        $this->view = Zend_Registry::get('view'); // 假設 bootstrap 已註冊 view
    }

    public function listAllAction() {
        $articles = $this->article->listAll();
        $this->view->articles = $articles;
        $this->view->title = '文章列表';
        // 渲染 scripts/article/listAll.phtml
    }

    public function viewAction() {
        $id = (int)$this->_getParam('id', 0);
        $article = $this->article->getById($id);
        if (!$article) {
            $this->_redirect('/article/listAll');
            return;
        }
        $this->view->article = $article;
    }
}
?>

4. 視圖腳本:純粹渲染

<!-- application/views/scripts/article/listAll.phtml -->
<h1>escape($this->title) ?></h1>
<table class="table">
    <thead>
        <tr><th>ID</th><th>標題</th><th>分類</th><th>作者</th><th>發布時間</th></tr>
    </thead>
    <tbody>
    articles as $article): ?>
        <tr>
            <td></td>
            <td><a href="/article/view/id/">escape($article['articletitle']) ?></a></td>
            <td></td>
            <td>escape($article['authorname']) ?></td>
            <td></td>
        </tr>
    
    </tbody>
</table>

Zend_Db 核心操作速查表

操作方法範例
查詢單行fetchRow()$db->fetchRow('SELECT * FROM t WHERE id=?', [$id])
查詢多行fetchAll()$db->fetchAll('SELECT * FROM t WHERE status=?', ['active'])
查詢單值fetchOne()$db->fetchOne('SELECT COUNT(*) FROM t')
查詢單欄fetchCol()$db->fetchCol('SELECT id FROM t')
插入資料insert()$db->insert('t', ['col1'=>'val1', 'col2'=>'val2'])
更新資料update()$db->update('t', ['col1'=>'new'], 'id=5')
刪除資料delete()$db->delete('t', 'id=5')
預處理執行query() + 參數陣列$db->query('SELECT * FROM t WHERE a=? AND b=?', [$a, $b])
事務控制beginTransaction()/commit()/rollBack()$db->beginTransaction(); ... $db->commit();
引用識別符quoteIdentifier()$db->quoteIdentifier('order') → `order`

常見問題與解決

1. "Could not find adapter class" 錯誤

確認 Zend_Db::factory() 第一參數為 'Pdo_Mysql'(大小寫敏感),且 php_pdo_mysql.dll 已載入。

2. 中文亂碼

連線參數加入 'charset' => 'utf8' 及 PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8';資料表/欄位字符集設為 utf8mb4。

3. SQL 注入防護

嚴禁字串拼接 SQL。永遠使用 ? 佔位符或命名參數 :name,配合 fetchAll()、query()、insert() 等方法自動綁定。

4. 除錯 SQL

$db->getProfiler()->setEnabled(true);
// 執行查詢後
foreach ($db->getProfiler()->getQueryProfiles() as $profile) {
    echo $profile->getQuery() . "\n"; // 顯示實際執行 SQL 含參數
}

結語

Zend_Db 以 適配器模式 統一資料庫操作,配合 Zend_Registry 實現連線共享,提供豐富的查詢方法與防注入機制。掌握「入口建立連線 → 註冊表存取 → 模型封裝查詢 → 控制器協調 → 視圖渲染」完整鏈路,即可在 ZF1 專案中高效、安全地操作 MySQL。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved