萬盛學電腦網

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

PHP 快速入門教學(二):新增、列表與資料庫操作

承接上一篇,實作通訊錄系統的「新增」與「列表」功能,示範表單處理、資料驗證、PDO 預處理語句、分頁查詢與閃存訊息。

新增聯絡人 public/create.php

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

session_start();
$pdo = Database::getInstance();
$errors = [];
$old = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF 驗證
    if (!csrf_check($_POST['csrf_token'] ?? '')) {
        $errors[] = '無效的請求,請重新提交';
    }
    
    // 取得並清理輸入
    $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');
    
    // 驗證規則
    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[] = '地址不可超過 200 字元';
    
    // 通過驗證:寫入資料庫
    if (empty($errors)) {
        try {
            $stmt = $pdo->prepare('
                INSERT INTO `contacts` (`name`, `gender`, `mobile`, `email`, `address`)
                VALUES (?, ?, ?, ?, ?)
            ');
            $stmt->execute([$name, $gender, $mobile, $email, $address]);
            
            flash('聯絡人新增成功!', 'success');
            redirect('index.php');
        } catch (PDOException $e) {
            $errors[] = '資料庫錯誤:' . $e->getMessage();
        }
    }
}

// 顯示表單
$page_title = '新增聯絡人';
include __DIR__ . '/../templates/header.php';
?>

<h1>新增聯絡人</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) === 0 ? 'checked' : '' ?>> 女</label>
        <label><input type="radio" name="gender" value="1" <?= ($old['gender'] ?? 0) === 1 ? 'checked' : '' ?>> 男</label>
        <label><input type="radio" name="gender" value="2" <?= ($old['gender'] ?? 0) === 2 ? 'checked' : '' ?>> 其他</label>
    </div>
    
    <div class="form-group">
        <label>手機</label>
        <input type="tel" name="mobile" value="<?= h($old['mobile'] ?? '') ?>" maxlength="20" placeholder="0912-345678">
    </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/index.php

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

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

// 分頁參數
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 15;
$offset = ($page - 1) * $per_page;

// 搜尋參數
$search = trim($_GET['q'] ?? '');
$where = '';
$params = [];

if ($search !== '') {
    $where = 'WHERE `name` LIKE ? OR `mobile` LIKE ? OR `email` LIKE ?';
    $term = "%{$search}%";
    $params = [$term, $term, $term];
}

// 總筆數
$count_stmt = $pdo->prepare("SELECT COUNT(*) FROM `contacts` {$where}");
$count_stmt->execute($params);
$total = $count_stmt->fetchColumn();
$total_pages = (int)ceil($total / $per_page);

// 修正頁碼
if ($page > $total_pages) $page = max(1, $total_pages);
$offset = ($page - 1) * $per_page;

// 取得資料
$stmt = $pdo->prepare("
    SELECT * FROM `contacts` {$where}
    ORDER BY `created_at` DESC
    LIMIT {$per_page} OFFSET {$offset}
");
$stmt->execute($params);
$contacts = $stmt->fetchAll();

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

<div class="d-flex justify-between align-center mb-3">
    <h1>聯絡人列表 <small>(共 <?= $total ?> 筆)</small></h1>
    <a href="create.php" class="btn btn-primary">+ 新增聯絡人</a>
</div>

<!-- 搜尋表單 -->
<form method="get" class="mb-3">
    <div class="input-group">
        <input type="search" name="q" value="<?= h($search) ?>" placeholder="搜尋姓名、手機、Email..." class="form-control">
        <button type="submit" class="btn btn-outline">搜尋</button>
        <?php if ($search): ?><a href="index.php" class="btn btn-outline">重置</a><?php endif; ?>
    </div>
</form>

<?php if (!empty($contacts)): ?>
<table class="table">
    <thead>
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>性別</th>
            <th>手機</th>
            <th>Email</th>
            <th>地址</th>
            <th>建立時間</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($contacts as $c): ?>
        <tr>
            <td><?= $c['id'] ?></td>
            <td><?= h($c['name']) ?></td>
            <td>
                <?= ['女', '男', '其他'][$c['gender']] ?>
            </td>
            <td><?= h($c['mobile']) ?></td>
            <td><?= h($c['email']) ?></td>
            <td><?= h($c['address']) ?></td>
            <td><?= $c['created_at'] ?></td>
            <td>
                <a href="edit.php?id=<?= $c['id'] ?>" class="btn btn-sm">編輯</a>
                <a href="delete.php?id=<?= $c['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('確定刪除?')">刪除</a>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<!-- 分頁導航 -->
<nav aria-label="分頁">
    <ul class="pagination">
        <?php if ($page > 1): ?>
            <li><a href="?page=1<?= $search ? '&q=' . urlencode($search) : '' ?>">首頁</a></li>
            <li><a href="?page=<?= $page-1 ?><?= $search ? '&q=' . urlencode($search) : '' ?>">上一頁</a></li>
        <?php endif; ?>
        
        <?php for ($p = max(1, $page-2); $p <= min($total_pages, $page+2); $p++): ?>
            <li class="<?= $p === $page ? 'active' : '' ?>">
                <a href="?page=<?= $p ?><?= $search ? '&q=' . urlencode($search) : '' ?>"><?= $p ?></a>
            </li>
        <?php endfor; ?>
        
        <?php if ($page < $total_pages): ?>
            <li><a href="?page=<?= $page+1 ?><?= $search ? '&q=' . urlencode($search) : '' ?>">下一頁</a></li>
            <li><a href="?page=<?= $total_pages ?><?= $search ? '&q=' . urlencode($search) : '' ?>">末頁</a></li>
        <?php endif; ?>
    </ul>
</nav>

<?php else: ?>
    <div class="alert alert-info">尚無聯絡人資料,<a href="create.php">立即新增</a></div>
<?php endif; ?>

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

版面模板 templates/header.php / footer.php

<!-- templates/header.php -->
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= h($page_title ?? '通訊錄') ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>.d-flex{display:flex}.justify-between{justify-content:space-between}.align-center{align-items:center}.mb-3{margin-bottom:1rem}.btn{padding:.5rem 1rem;border-radius:.25rem;text-decoration:none;display:inline-block}.btn-primary{background:#0d6efd;color:#fff}.btn-secondary{background:#6c757d;color:#fff}.btn-danger{background:#dc3545;color:#fff}.btn-sm{padding:.25rem .5rem;font-size:.875rem}.btn-outline{border:1px solid #0d6efd;color:#0d6efd;background:transparent}.form-group{margin-bottom:1rem}label{display:block;margin-bottom:.25rem;font-weight:500}input,select,textarea{width:100%;padding:.5rem;border:1px solid #ced4da;border-radius:.25rem}.alert{padding:1rem;border-radius:.25rem;margin-bottom:1rem}.alert-danger{background:#f8d7da;color:#721c24;border:1px solid #f5c6cb}.alert-success{background:#d1e7dd;color:#0f5132;border:1px solid #badbcc}.alert-info{background:#cff4fc;color:#055160;border:1px solid #b6effb}.table{width:100%;border-collapse:collapse}.table th,.table td{padding:.5rem;border:1px solid #dee2e6}.pagination{display:flex;gap:.25rem;list-style:none}.pagination a{padding:.375rem .75rem;border:1px solid #dee2e6;text-decoration:none}.pagination .active a{background:#0d6efd;color:#fff;border-color:#0d6efd}.input-group{display:flex;gap:.5rem}
<!-- templates/footer.php -->
    <hr>
    <footer class="text-center text-muted small">
        © <?= date('Y') ?> 通訊錄管理系統
    </footer>
</body>
</html>

關鍵學習重點

  1. PDO Prepared Statements:prepare() + execute([...]) 防 SQL 注入
  2. 輸入驗證:型別轉換、長度限制、格式檢查、白名單
  3. CSRF 保護:Session Token + 表單隱藏欄位 + hash_equals() 驗證
  4. 閃存訊息:Session 暫存、顯示後立即清除
  5. 分頁查詢:COUNT(*) 取總數 → 計算總頁數 → LIMIT ... OFFSET
  6. 搜尋功能:LIKE + 參數綁定,保留搜尋條件於分頁連結
  7. 輸出跳脫:h() 包裝 htmlspecialchars() 防 XSS
  8. 錯誤處理:try-catch 捕獲 PDOException,友善回饋

完成新增與列表,下一篇將實作編輯與刪除功能。

copyright © 萬盛學電腦網 all rights reserved