萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 快速入門教學(三):編輯、刪除與專案完結

完成通訊錄系統最後兩項核心功能:編輯更新與刪除確認,並整理專案重構重點與學習路徑建議。

編輯聯絡人 public/edit.php

<?php
require_once __DIR__ . '/../src/Database.php';
require_once __DIR__ . '/../src/functions.php';

session_start();
$pdo = Database::getInstance();

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    flash('無效的 ID', 'danger');
    redirect('index.php');
}

// 取得原資料
$stmt = $pdo->prepare('SELECT * FROM `contacts` WHERE `id` = ?');
$stmt->execute([$id]);
$contact = $stmt->fetch();

if (!$contact) {
    flash('找不到該聯絡人', 'danger');
    redirect('index.php');
}

$errors = [];
$old = $contact; // 預填原資料

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_check($_POST['csrf_token'] ?? '')) {
        $errors[] = '無效的請求';
    } else {
        $name    = trim($_POST['name'] ?? '');
        $gender  = (int)($_POST['gender'] ?? 0);
        $mobile  = trim($_POST['mobile'] ?? '');
        $email   = trim($_POST['email'] ?? '');
        $address = trim($_POST['address'] ?? '');
        
        $old = compact('name', 'gender', 'mobile', 'email', 'address');
        
        // 驗證(同 create.php)
        if ($name === '') $errors[] = '姓名為必填';
        elseif (mb_strlen($name) > 50) $errors[] = '姓名不可超過 50 字元';
        if (!in_array($gender, [0,1,2], true)) $errors[] = '性別值無效';
        if ($mobile !== '' && !preg_match('/^\+?[\d\s-]{8,20}$/', $mobile)) $errors[] = '手機格式錯誤';
        if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Email 格式錯誤';
        if (mb_strlen($address) > 200) $errors[] = '地址過長';
        
        if (empty($errors)) {
            try {
                $stmt = $pdo->prepare('
                    UPDATE `contacts` SET 
                        `name` = ?, `gender` = ?, `mobile` = ?, `email` = ?, `address` = ?
                    WHERE `id` = ?
                ');
                $stmt->execute([$name, $gender, $mobile, $email, $address, $id]);
                
                flash('聯絡人更新成功!', 'success');
                redirect('index.php');
            } catch (PDOException $e) {
                $errors[] = '資料庫錯誤:' . $e->getMessage();
            }
        }
    }
}

$page_title = '編輯聯絡人';
include __DIR__ . '/../templates/header.php';
?>

<h1>編輯聯絡人:<?= h($contact['name']) ?></h1>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <ul><?php foreach ($errors as $e): ?><li><?= h($e) ?></li><?php endforeach; ?></ul>
    </div>
<?php endif; ?>

<form method="post" novalidate>
    <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
    
    <div class="form-group">
        <label>姓名 *</label>
        <input type="text" name="name" value="<?= h($old['name']) ?>" required maxlength="50">
    </div>
    
    <div class="form-group">
        <label>性別</label>
        <label><input type="radio" name="gender" value="0" <?= $old['gender']==0?'checked':'' ?>> 女</label>
        <label><input type="radio" name="gender" value="1" <?= $old['gender']==1?'checked':'' ?>> 男</label>
        <label><input type="radio" name="gender" value="2" <?= $old['gender']==2?'checked':'' ?>> 其他</label>
    </div>
    
    <div class="form-group">
        <label>手機</label>
        <input type="tel" name="mobile" value="<?= h($old['mobile']) ?>" maxlength="20">
    </div>
    
    <div class="form-group">
        <label>Email</label>
        <input type="email" name="email" value="<?= h($old['email']) ?>" maxlength="100">
    </div>
    
    <div class="form-group">
        <label>地址</label>
        <input type="text" name="address" value="<?= h($old['address']) ?>" maxlength="200">
    </div>
    
    <button type="submit" class="btn btn-primary">更新</button>
    <a href="index.php" class="btn btn-secondary">取消</a>
</form>

<?php include __DIR__ . '/../templates/footer.php'; ?>

刪除聯絡人 public/delete.php

<?php
require_once __DIR__ . '/../src/Database.php';
require_once __DIR__ . '/../src/functions.php';

session_start();
$pdo = Database::getInstance();

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    flash('無效的 ID', 'danger');
    redirect('index.php');
}

// 取得資料供確認頁顯示
$stmt = $pdo->prepare('SELECT `name` FROM `contacts` WHERE `id` = ?');
$stmt->execute([$id]);
$contact = $stmt->fetch();

if (!$contact) {
    flash('找不到該聯絡人', 'danger');
    redirect('index.php');
}

// POST 確認刪除
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_check($_POST['csrf_token'] ?? '')) {
        flash('無效的請求', 'danger');
    } else {
        try {
            $stmt = $pdo->prepare('DELETE FROM `contacts` WHERE `id` = ?');
            $stmt->execute([$id]);
            
            if ($stmt->rowCount() > 0) {
                flash('聯絡人已刪除', 'success');
            } else {
                flash('刪除失敗,資料不存在', 'danger');
            }
        } catch (PDOException $e) {
            flash('資料庫錯誤:' . $e->getMessage(), 'danger');
        }
        redirect('index.php');
    }
}

$page_title = '刪除確認';
include __DIR__ . '/../templates/header.php';
?>

<h1>確認刪除</h1>

<div class="alert alert-warning">
    <p>確定要刪除聯絡人 <?= h($contact['name']) ?> 嗎?此操作無法復原。</p>
</div>

<form method="post">
    <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
    <button type="submit" class="btn btn-danger">確定刪除</button>
    <a href="index.php" class="btn btn-secondary">取消</a>
</form>

<?php include __DIR__ . '/../templates/footer.php'; ?>

專案重構重點(從教學到生產級)

1. 採用 MVC 架構分層

src/
├── Controller/
│   ├── ContactController.php  # 處理請求、協調 Model/View
├── Model/
│   ├── Contact.php            # Eloquent/ActiveRecord 風格模型
│   └── ContactRepository.php  # 資料存取邏輯
├── View/
│   └── (Twig/Blade/原生 PHP 模板)
├── Service/                   # 業務邏輯
├── Middleware/                # Auth、CSRF、RateLimit
└── Router.php                 # 路由分發

2. 引入現代工具鏈

領域推薦工具用途
框架Laravel / Slim / Symfony路由、DI 容器、中介層、ORM
ORMEloquent / Doctrine物件關聯對映、關聯查詢、遷移
模板引擎Blade / Twig / Latte繼承、區塊、自動跳脫、安全
驗證Respect\Validation / Laravel Validator聲明式驗證規則、錯誤訊息
遷移Phinx / Laravel Migrations版本化資料庫結構
測試Pest / PHPUnit單元/功能/整合測試
靜態分析PHPStan / Psalm型別檢查、死碼偵測
代碼風格PHP-CS-Fixer / Pint統一風格、自動修正

3. 安全性清單

  • ☐ 所有輸出經 htmlspecialchars() / 模板引擎自動跳脫
  • ☐ 所有 SQL 使用 Prepared Statements
  • ☐ 密碼雜湊 password_hash()、驗證 password_verify()
  • ☐ CSRF Token 保護所有狀態變更操作
  • ☐ 檔案上傳:型態驗證、重新命名、隔離儲存、禁用執行權限
  • ☐ HTTP Headers:CSP、HSTS、X-Frame-Options、Referrer-Policy
  • ☐ 速率限制:登入、API、表單提交
  • ☐ 敏感資料不記錄 Log(密碼、Token、信用卡)

4. 效能優化

  • 資料庫索引優化、查詢計畫分析 EXPLAIN
  • Redis 快取熱門查詢、Session、佇列
  • OPcache / JIT 啟用、Composer Classmap 優化
  • CDN 靜態資源、HTTP/2、Gzip/Brotli 壓縮
  • N+1 問題:Eager Loading / Join 查詢

學習路徑建議

  1. 基礎語法:變數、陣列、函數、類別、介面、Trait、命名空間、Composer
  2. 資料庫:SQL、索引、正規化、交易、PDO、遷移
  3. Web 基礎:HTTP、Cookie/Session、CORS、REST API 設計
  4. 框架實戰:Laravel 完整專案(認證、授權、佇列、排程、測試)
  5. 進階主題:設計模式、SOLID、DDD、微服務、容器化、觀測性
  6. 持續精進:閱讀原始碼、參與開源、技術部落格、技術分享

完整專案結構回顧

address_book/
├── public/
│   ├── index.php      ✅ 列表、搜尋、分頁
│   ├── create.php     ✅ 新增表單、驗證、寫入
│   ├── edit.php       ✅ 編輯表單、更新
│   ├── delete.php     ✅ 刪除確認、執行
│   └── assets/
├── src/
│   ├── Database.php   ✅ PDO Singleton
│   └── functions.php  ✅ h(), redirect(), flash(), csrf_*()
├── templates/
│   ├── header.php     ✅ 共用頭部、閃存訊息
│   └── footer.php     ✅ 共用尾部
├── config.php         ✅ 環境設定
└── composer.json

恭喜完成 PHP 入門三部曲!你已經掌握 CRUD 核心流程、安全基礎與專案結構。下一步建議:嘗試用 Laravel 重寫此專案,體驗現代框架的開發效率與最佳實踐。

copyright © 萬盛學電腦網 all rights reserved