萬盛學電腦網

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

ASP 表單處理與資料庫寫入範例:身分證字號驗證邏輯

程式碼說明

此為經典 ASP (VBScript) 程式碼片段,示範表單資料接收、基本驗證、資料庫寫入流程。注意:此為 ASP 非 PHP 程式碼,僅供參考舊系統遷移或對照學習。

核心流程

  1. 檢查 postyes=1 確認表單提交。
  2. 使用 SafeRequest() 取得並清理所有輸入欄位(防止 SQL Injection/XSS)。
  3. 必填欄位驗證:用戶名、公司、證件類型、證號、電話、地址、加入日期、公司 ID。
  4. 驗證失敗輸出 JavaScript 警示並 history.go(-1) 返回。
  5. 使用 ADODB.Recordset 開啟 UserDic 資料表,AddNew 寫入所有欄位。
  6. 寫入成功後導向 reg.asp 並帶入 comid 參數。

關鍵程式碼片段

<%
if request("postyes") = "1" then
    ' 取得並清理輸入
    leixing   = SafeRequest("leixing", 2)
    userName  = SafeRequest("userName", 2)
    thecom    = SafeRequest("thecom", 2)
    CodeType  = SafeRequest("CodeType", 2)
    Code      = SafeRequest("Code", 2)
    Tel       = SafeRequest("Tel", 2)
    ' ... 其他欄位 ...

    ' 必填驗證
    if userName="" or thecom="" or CodeType="" or Code="" or Tel="" or Add="" or joinDate="" or ScomID="" then
        response.Write("")
        response.End()
    end if

    ' 資料庫寫入
    set rs = server.CreateObject("adodb.recordset")
    sql = "select * from UserDic"
    rs.open sql, conn, 1, 3  ' adOpenKeyset, adLockOptimistic
    rs.addnew
    rs("leixing")   = leixing
    rs("userName")  = userName
    rs("thecom")    = thecom
    rs("CodeType")  = CodeType
    rs("Code")      = Code
    rs("Tel")       = Tel
    ' ... 其他欄位 ...
    rs("state")     = 0
    rs.update

    response.Write("")
end if
%>

安全性提醒

  • SafeRequest() 應包含:SQL 轉義、HTML 編碼、長度限制、型別檢查。
  • 生產環境建議改用參數化查詢(Command + Parameters)替代 Recordset 直接寫入。
  • 身分證字號(Code)驗證邏輯未在片段中,實務需加入格式與檢查碼驗證。

PHP 對應寫法參考

<?php
// PDO 參數化寫入範例
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $required = ['userName', 'thecom', 'CodeType', 'Code', 'Tel', 'Add', 'joinDate', 'ScomID'];
    foreach ($required as $field) {
        if (empty($_POST[$field])) {
            die("欄位 $field 為必填");
        }
    }
    
    $stmt = $pdo->prepare("INSERT INTO UserDic (leixing, userName, thecom, CodeType, Code, Tel, Fox, Add, Email, PostCode, joinDate, ScomID, instrtxt, yongtu, SelectA, SelectB, userType, state) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0)");
    $stmt->execute([
        $_POST['leixing'], $_POST['userName'], $_POST['thecom'], $_POST['CodeType'],
        $_POST['Code'], $_POST['Tel'], $_POST['Fox'], $_POST['Add'],
        $_POST['Email'], $_POST['PostCode'], $_POST['joinDate'], $_POST['ScomID'],
        $_POST['instrtxt'], $_POST['yongtu'], $_POST['SelectA'], $_POST['SelectB'],
        $_POST['userType']
    ]);
    echo "提交成功";
}
?>

現代 Web 開發建議採用 PHP + PDO / MySQLi,搭配前端驗證與後端雙重防護,確保資料完整與安全。

copyright © 萬盛學電腦網 all rights reserved