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

ThinkPHP快速構建留言板:留言、驗證、分頁功能完整實現

     編輯:PHP 綜合知識

項目背景

利用ThinkPHP框架開發一個輕量級留言板,核心功能包含留言提交、表單驗證、分頁顯示。得益於框架封裝,控制器與模型代碼極其精簡。

控制器實現

class IndexAction extends Action {
    public function index() {
        $Form = M("word"); // 實例化模型
        import("@.ORG.Page"); // 載入分頁類
        $count = $Form->count(); // 總記錄數
        $p = new Page($count, 1); // 每頁1條(演示用)
        $list = $Form->limit($p->firstRow . ',' . $p->listRows)
                     ->order('id desc')
                     ->findAll();
        $page = $p->show(); // 生成分頁導航
        $this->assign("page", $page);
        $this->assign("list", $list);
        $this->display(); // 渲染模板
    }

    // 數據插入
    public function insert() {
        $word = D("word");
        if ($vo = $word->create()) {
            if (false !== $word->add()) {
                $this->success("數據添加成功");
            } else {
                $this->error('數據寫入錯誤!');
            }
        } else {
            $this->error($word->getError());
        }
    }

    // AJAX驗證用戶名唯一性
    public function checkTitle() {
        if (!empty($_POST['username'])) {
            $Form = M("word");
            if ($Form->getByUsername($_POST['username'])) {
                $this->error('<font color=red>標題已經存在</font>');
            } else {
                $this->success('標題可以使用!');
            }
        } else {
            $this->error('標題必須');
        }
    }
}

模型驗證與自動完成

class wordModel extends Model {
    protected $_validate = array(
        array('username', 'require', '稱呼必須!', 1),
        array('email', 'email', '郵箱格式錯誤!', 2),
        array('qq', 'number', 'QQ號錯誤', 2),
        array('content', 'require', '內容必須', 1),
        array('username', '', '稱呼已經存在', 0, 'unique', 1)
    );

    protected $_auto = array(
        array('datetime', 'get_date', 1, 'callback'),
        array('ip', 'getip', 1, 'callback')
    );

    protected function get_date() {
        return date("Y-m-d H:i:s");
    }
    protected function getip() {
        return $_SERVER['REMOTE_ADDR'];
    }
}

關鍵點提示

ThinkPHP的CURD操作需注意表名規範,模型自動驗證與自動完成大幅減少控制器邏輯。更多框架技巧請參考專題《ThinkPHP常用方法總結》。

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