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

ThinkPHP 框架 CRUD 實戰入門:從模型操作到模板渲染

     編輯:PHP 相關知識

以 ThinkPHP 3.x 為例,示範 User 模組的基本增刪改查流程。

控制器:UserAction.class.php

<?php
class UserAction extends Action {
    // 列表頁
    public function index() {
        $model = M('User');           // 實例化 User 模型
        $data  = $model->select();    // 查詢所有資料
        $this->assign('data', $data); // 指派變數給模板
        $this->display();             // 渲染 index.html
    }

    // 處理新增表單提交
    public function add() {
        $model = M('User');
        $model->username = $_POST['username'];
        $model->sex      = $_POST['sex'];
        
        $result = $model->add();      // 寫入資料庫
        
        if ($result) {
            $this->success('新增成功', 'index'); // 成功導向列表頁
        } else {
            $this->error('新增失敗');
        }
    }

    // 顯示新增表單頁
    public function addform() {
        $this->display(); // 渲染 addform.html
    }
}

模板:index.html(列表頁)

<html>
<head>
    <title>使用者列表</title>
    <script>
        function toAddForm() {
            window.location = '__URL__/addform';
        }
    </script>
</head>
<body>
    <table border="1">
        <tr>
            <th>ID</th><th>使用者名稱</th><th>性別</th><th>操作</th>
        </tr>
        <volist name="data" id="vo">
        <tr>
            <td>{$vo.id}</td>
            <td>{$vo.username}</td>
            <td>{$vo.sex}</td>
            <td><a href="__URL__/edit/id/{$vo.id}">修改</a> | <a href="__URL__/delete/id/{$vo.id}">刪除</a></td>
        </tr>
        </volist>
    </table>
    <button onclick="toAddForm()">新增使用者</button>
</body>
</html>

模板:addform.html(新增表單)

<html>
<head><title>新增使用者</title></head>
<body>
    <form action="__URL__/add" method="post">
        使用者名稱:<input type="text" name="username" required><br>
        性別:
        <select name="sex">
            <option value="1">男</option>
            <option value="2">女</option>
        </select><br>
        <input type="submit" value="提交">
    </form>
</body>
</html>

關鍵點總結

方法用途
M('Table')實例化模型,對應資料表
$model->select()查詢多筆資料
$model->find()查詢單筆資料
$model->add()新增資料,回傳自增 ID
$model->save()更新資料
$model->delete()刪除資料
$this->assign()指派變數給模板
$this->display()渲染模板
$this->success/error()跳轉提示

進階補充

  • 資料驗證:模型類別定義 $_validate 陣列自動驗證
  • 自動完成:$_auto 陣列處理建立/更新時間等欄位
  • 分頁查詢:$model->limit($offset, $rows)->select()
  • 條件查詢:$model->where('sex=1')->select()
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved