萬盛學電腦網

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

PHP 入門實戰:MySQL 資料庫 CRUD 完整範例 (連線、建表、新增、查詢、刪除)

專案結構規劃

project/
├── config.php      # 資料庫連線設定
├── create_db.php   # 建立資料庫與資料表
├── insert.php      # 新增資料表單
├── insert_ok.php   # 處理新增邏輯
├── view.php        # 顯示資料列表
├── edit.php        # 編輯表單 (延伸)
├── update.php      # 處理更新 (延伸)
└── delete.php      # 刪除處理 (延伸)

1. 資料庫連線設定 (config.php)

<?php
// config.php
$host = 'localhost';
$user = 'root';
$pass = 'password';
$dbname = 'link_system';

// 建立連線 (mysqli 程序式,建議改用 PDO)
$link = mysqli_connect($host, $user, $pass);
if (!$link) {
    die('連線失敗: ' . mysqli_connect_error());
}

// 設定字元集 (防止中文亂碼)
mysqli_set_charset($link, 'utf8mb4');
?>

重要:原文使用已移除的 mysql_* 函數,本文升級為 mysqli_* 並加入字元集設定。

2. 建立資料庫與資料表 (create_db.php)

<?php
require_once 'config.php';

// 建立資料庫
$sqlDb = "CREATE DATABASE IF NOT EXISTS `$dbname` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci";
if (mysqli_query($link, $sqlDb)) {
    echo "資料庫建立成功或已存在<br>";
} else {
    die("資料庫建立失敗: " . mysqli_error($link));
}

// 選擇資料庫
mysqli_select_db($link, $dbname);

// 建立友情連結表
$sqlTable = "
CREATE TABLE IF NOT EXISTS `link_table` (
    `link_id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `link_name` VARCHAR(100) NOT NULL,
    `link_url` VARCHAR(255) NOT NULL,
    `link_detail` VARCHAR(500) DEFAULT '',
    `link_contact` VARCHAR(100) DEFAULT '',
    `link_show` TINYINT UNSIGNED NOT NULL DEFAULT 1,
    `link_order` INT UNSIGNED NOT NULL DEFAULT 0,
    `link_sort` INT UNSIGNED NOT NULL DEFAULT 0,
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
";
if (mysqli_query($link, $sqlTable)) {
    echo "link_table 建立成功<br>";
} else {
    echo "建立失敗: " . mysqli_error($link);
}

// 建立分類表
$sqlSort = "
CREATE TABLE IF NOT EXISTS `sort_table` (
    `sort_id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `sort_name` VARCHAR(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
";
mysqli_query($link, $sqlSort) ? echo "sort_table 建立成功" : echo "失敗: " . mysqli_error($link);

mysqli_close($link);
?>

3. 新增資料表單 (insert.php)

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>新增友情連結</title></head>
<body>
<h2>新增友情連結</h2>
<form action="insert_ok.php" method="POST">
    網站名稱: <input type="text" name="link_name" required><br><br>
    網站網址: <input type="url" name="link_url" value="https://" required><br><br>
    簡介: <input type="text" name="link_detail" placeholder="無"><br><br>
    聯絡方式: <input type="text" name="link_contact"><br><br>
    排序: <input type="number" name="link_order" value="0" min="0"><br><br>
    分類ID: <input type="number" name="link_sort" value="0" min="0"><br><br>
    是否顯示: <input type="checkbox" name="link_show" value="1" checked><br><br>
    <input type="submit" value="送出">
</form>
</body>
</html>

4. 處理新增邏輯 (insert_ok.php)

<?php
require_once 'config.php';

// 1. 接收並清理輸入
$name = trim($_POST['link_name'] ?? '');
$url = trim($_POST['link_url'] ?? '');
$detail = trim($_POST['link_detail'] ?? '');
$contact = trim($_POST['link_contact'] ?? '');
$order = (int)($_POST['link_order'] ?? 0);
$sort = (int)($_POST['link_sort'] ?? 0);
$show = isset($_POST['link_show']) ? 1 : 0;

// 2. 基本驗證
if (empty($name) || empty($url)) {
    die('名稱與網址為必填');
}
if (!filter_var($url, FILTER_VALIDATE_URL)) {
    die('網址格式錯誤');
}

// 3. 預處理語句 (防止 SQL Injection) - 核心安全實踐
$stmt = mysqli_prepare($link, "
    INSERT INTO link_table (link_name, link_url, link_detail, link_contact, link_order, link_sort, link_show)
    VALUES (?, ?, ?, ?, ?, ?, ?)
");
mysqli_stmt_bind_param($stmt, 'ssssiii', $name, $url, $detail, $contact, $order, $sort, $show);

if (mysqli_stmt_execute($stmt)) {
    echo "新增成功!ID: " . mysqli_insert_id($link);
} else {
    echo "新增失敗: " . mysqli_stmt_error($stmt);
}

mysqli_stmt_close($stmt);
mysqli_close($link);
?>

5. 顯示資料列表 (view.php)

<?php
require_once 'config.php';

$sql = "SELECT * FROM link_table WHERE link_show = 1 ORDER BY link_order ASC, link_id ASC";
$result = mysqli_query($link, $sql);

if (!$result) {
    die('查詢失敗: ' . mysqli_error($link));
}
?>
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>友情連結列表</title></head>
<body>
<h2>友情連結</h2>
<ul>
<?php while ($row = mysqli_fetch_assoc($result)): ?>
    <li>
        <a href="<?= htmlspecialchars($row['link_url']) ?>" target="_blank" title="<?= htmlspecialchars($row['link_detail'] ?: $row['link_name']) ?>">
            <?= htmlspecialchars($row['link_name']) ?>
        </a>
    </li>
<?php endwhile; ?>
</ul>
<?php
mysqli_free_result($result);
mysqli_close($link);
?>
</body>
</html>

6. 刪除功能延伸 (delete.php)

<?php
require_once 'config.php';
$id = (int)($_GET['id'] ?? 0);
if ($id > 0) {
    $stmt = mysqli_prepare($link, "DELETE FROM link_table WHERE link_id = ? LIMIT 1");
    mysqli_stmt_bind_param($stmt, 'i', $id);
    mysqli_stmt_execute($stmt) ? header('Location: view.php') : die('刪除失敗');
    mysqli_stmt_close($stmt);
}
mysqli_close($link);
?>

在 view.php 列表中加入刪除連結:<a href="delete.php?id=<?=$row['link_id']?>" onclick="return confirm('確定刪除?')>刪除</a>

關鍵安全與最佳實踐總結

  1. 棄用 mysql_* 改用 mysqli/PDO,並使用預處理語句防 SQL Injection。
  2. 輸出轉義:htmlspecialchars() 防 XSS。
  3. 輸入驗證/過濾:filter_var(), (int), trim()。
  4. 字元集統一 utf8mb4:支援 Emoji 完整 Unicode。
  5. 錯誤處理:開發環境顯示錯誤,生產環境記錄日誌不顯示細節。

結語

這個 CRUD 範例涵蓋 PHP + MySQL 開發最核心的流程。實務專案建議進一步導入:PDO 抽象層、分頁類別、表單驗證庫、模板引擎 (Twig/Blade)、框架 (Laravel/CodeIgniter) 以提升開發效率與安全性。

copyright © 萬盛學電腦網 all rights reserved