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

PHP MySQL 資料刪除操作範例(使用 MySQLi)

     編輯:PHP 相關知識

PHP MySQL 資料刪除操作範例

展示透過 GET 參數取得 ID、預備語句刪除、顯示影響列數、錯誤處理與列表頁面整合的完整流程。

完整程式碼

<?php
$host = 'localhost';
$user = 'root';
$pass = 'password';
$db   = 'phpdev';

$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_errno) {
    die('連線失敗:' . $mysqli->connect_error);
}
$mysqli->set_charset('utf8mb4');

$message = '';

// 處理刪除請求
if (isset($_GET['id'])) {
    $id = (int)$_GET['id']; // 強制轉整數,基本防注入
    if ($id > 0) {
        $stmt = $mysqli->prepare('DELETE FROM symbols WHERE id = ?');
        $stmt->bind_param('i', $id);
        if ($stmt->execute()) {
            $affected = $stmt->affected_rows;
            $message = $affected ? "已刪除 $affected 筆資料" : '找不到指定 ID';
        } else {
            $message = '刪除失敗:' . $stmt->error;
        }
        $stmt->close();
    } else {
        $message = '無效的 ID';
    }
}

// 取得列表資料
$rows = [];
$result = $mysqli->query('SELECT id, country, animal, cname FROM symbols ORDER BY id');
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $result->free();
}
$mysqli->close();
?>
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>刪除資料示範</title></head>
<body>
<h1>動物資料管理 - 刪除</h1>

<?php if ($message): ?>
    <div style="color:<?= strpos($message,'失敗')!==false?'red':'green' ?>"><?= $message ?></div>
<?php endif; ?>

<table border="1" cellpadding="10">
    <thead>
        <tr><th>ID</th><th>國家</th><th>英文名</th><th>中文名</th><th>操作</th></tr>
    </thead>
    <tbody>
    <?php foreach ($rows as $row): ?>
        <tr>
            <td><?= $row['id'] ?></td>
            <td><?= htmlspecialchars($row['country']) ?></td>
            <td><?= htmlspecialchars($row['animal']) ?></td>
            <td><?= htmlspecialchars($row['cname']) ?></td>
            <td>
                <a href="?id=<?= $row['id'] ?>" onclick="return confirm('確定刪除 ID <?= $row['id'] ?> 嗎?')>刪除</a>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</body></html>

關鍵安全措施

  1. ID 型別轉換:(int)$_GET['id'] 確保為整數,阻擋 SQL 注入嘗試。
  2. 預備語句:prepare() + bind_param('i') 參數化查詢,徹底防注入。
  3. 確認對話框:JS confirm() 防止誤點。
  4. POST/DELETE 方法:實務上刪除操作應使用 POST 或 DELETE 方法,配合 CSRF Token,避免被爬蟲或預載觸發。

改進建議:使用 POST 表單

<!-- 列表頁改為表單 -->
<form method="post" action="delete.php" onsubmit="return confirm('確定刪除?')">
    <input type="hidden" name="id" value="<?= $row['id'] ?>">
    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
    <button type="submit">刪除</button>
</form>

delete.php 驗證 $_POST['csrf_token'] 後執行刪除,完成導回列表頁。

批次刪除擴充

// 前端:核取方塊 name="ids[]"
// 後端:
$ids = array_map('intval', $_POST['ids'] ?? []);
if ($ids) {
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $types = str_repeat('i', count($ids));
    $stmt = $mysqli->prepare("DELETE FROM symbols WHERE id IN ($placeholders)");
    $stmt->bind_param($types, ...$ids);
    $stmt->execute();
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved