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

PHP 向 MySQL 發送資料完整流程:HTML 表單、GET/POST、資料庫寫入與驗證

     編輯:PHP 綜合知識

前端表單

<form action="submitform.php" method="GET">
  姓: <input type="text" name="first_name" size="25" maxlength="25">
  名: <input type="text" name="last_name" size="25" maxlength="25">
  <input type="submit">
</form>

後端處理 submitform.php

<?php
// 連線資料庫
mysql_connect("localhost", "username", "password");
mysql_select_db("dbname");

// 取得表單資料(PHP 自動建立同名變數)
// $first_name, $last_name

// 寫入資料庫
mysql_query("INSERT INTO tablename (first_name, last_name)
             VALUES ('$first_name', '$last_name')");

// 回應用戶
echo $first_name . " " . $last_name . "<p>感謝填寫註冊表</p>";
?>

資料流向說明

  1. 用戶填寫表單,按下提交。
  2. 瀏覽器依 method 發送請求:
    • GET:submitform.php?first_name=Fred&last_name=Flintstone(URL 可見,長度受限)。
    • POST:請求體攜帶資料(適合大量/敏感資料)。
  3. PHP 自動將表單欄位轉為同名變數($first_name, $last_name)。
  4. 腳本執行 SQL INSERT,資料寫入資料表。
  5. 驗證:mysql> SELECT * FROM tablename; 可見新增記錄。

安全警示(原文未處理,必須補強)

  • SQL 注入:直接插入變數極危險,必須使用 mysql_real_escape_string() 或預處理語句。
  • XSS:輸出用戶資料需 htmlspecialchars()。
  • 資料庫憑證:勿硬編碼,使用設定檔且不可公開。
  • mysql_* 函數已棄用:PHP 7 移除,請改用 mysqli 或 PDO。

現代化重寫範例

<?php
$pdo = new PDO("mysql:host=localhost;dbname=dbname;charset=utf8mb4", "user", "pass");
$stmt = $pdo->prepare("INSERT INTO tablename (first_name, last_name) VALUES (?, ?)");
$stmt->execute([$_POST['first_name'], $_POST['last_name']]);
echo htmlspecialchars($_POST['first_name']) . " " . htmlspecialchars($_POST['last_name']) . " 感謝註冊";
?>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved