從 PHP 環境啟用 MySQL 擴展,到建立資料庫連線類、處理表單 POST 資料、防範 SQL 注入,本文提供一份可直接落地的完整實作指南。
php_mysql.dll、libmysql.dll 到 C:\Windows\System32\php.ini,取消註解:extension=php_gd2.dll extension=php_mbstring.dll extension=php_mysql.dll extension=php_mysqli.dll
<?php
// conn.php
class DB {
private static $instance = null;
public $link;
private function __construct() {
$this->link = new mysqli("localhost", "root", "159357", "db_test");
if ($this->link->connect_errno) {
die("連線失敗: " . $this->link->connect_error);
}
$this->link->set_charset("utf8");
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}
?>
<!-- login.php --> <form action="add.php" method="post"> 用戶名: <input type="text" name="username" required><br> Email: <input type="email" name="email" required><br> <input type="submit" name="submit" value="提交"> </form>
<?php
// add.php
require_once 'conn.php';
$db = DB::getInstance()->link;
if (isset($_POST['submit'])) {
// 使用預處理防注入
$stmt = $db->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $_POST['username'], $_POST['email']);
if ($stmt->execute()) {
echo "新增成功,ID: " . $stmt->insert_id;
} else {
echo "錯誤: " . $stmt->error;
}
$stmt->close();
}
?>
| 錯誤寫法 | 風險 | 正確寫法 |
|---|---|---|
VALUES ('$_POST[username]') | SQL 注入 | 預處理 bind_param |
直接用 $_POST 未過濾 | XSS、資料汙染 | htmlspecialchars() 輸出時轉義 |
| 無 CSRF 保護 | 跨站請求偽造 | 表單加入 Token 驗證 |