萬盛學電腦網

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

PHP 插入 MySQL 資料庫完整指南:從基礎到防注入

原始代碼問題分析

<?php
// 原代碼片段
$result = mysql_query("INSERT INTO t_dblocal_userinformation (ID, OSTYPE, UUID, LASTDATE) VALUES (NULL, $ostype, $uuid, $nowtime)");

三大致命問題:

  1. 字串值未加引號:$ostype、$uuid、$nowtime 直接拼接,若為字串類型 SQL 語法錯誤。
  2. 時間格式不匹配:time() 返回 Unix 時間戳 (整數),資料庫 DATE 需 Y-m-d,DATETIME 需 Y-m-d H:i:s。
  3. SQL 注入風險極高:直接拼接用戶輸入 ($_POST),無任何過濾。

修正版:參數化查詢 (PDO,推薦標準)

<?php
// 配置
$dsn = 'mysql:host=localhost;dbname=your_db;charset=utf8mb4';
$user = 'db_user';
$pass = 'db_pass';

try {
    $pdo = new PDO($dsn, $user, $pass, [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false, // 真實預處理
    ]);

    // 輸入獲取與驗證
    $ostype = $_POST['ostype'] ?? '';
    $uuid   = $_POST['uuid']   ?? '';
    if (!$ostype || !$uuid) {
        throw new InvalidArgumentException('缺少必要參數');
    }

    // 時間格式化 (假設 LASTDATE 為 DATETIME)
    $now = (new DateTime())->format('Y-m-d H:i:s');

    // 參數化插入
    $sql = 'INSERT INTO t_dblocal_userinformation (OSTYPE, UUID, LASTDATE) VALUES (?, ?, ?)';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$ostype, $uuid, $now]);

    $id = $pdo->lastInsertId();
    echo json_encode(['code' => 1000, 'message' => '插入成功', 'id' => $id]);

} catch (PDOException $e) {
    // 生產環境不輸出具體錯誤,記錄日誌
    error_log('DB Insert Error: ' . $e->getMessage());
    echo json_encode(['code' => 1002, 'message' => '插入失敗']);
} catch (Exception $e) {
    echo json_encode(['code' => 1001, 'message' => $e->getMessage()]);
}

MySQLi 版本 (程序式風格)

<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'db');
$mysqli->set_charset('utf8mb4');

$ostype = $mysqli->real_escape_string($_POST['ostype'] ?? '');
$uuid   = $mysqli->real_escape_string($_POST['uuid'] ?? '');
$now    = date('Y-m-d H:i:s');

$sql = "INSERT INTO t_dblocal_userinformation (OSTYPE, UUID, LASTDATE) VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('sss', $ostype, $uuid, $now);

if ($stmt->execute()) {
    echo json_encode(['code' => 1000, 'id' => $stmt->insert_id]);
} else {
    echo json_encode(['code' => 1002, 'message' => '執行失敗: ' . $stmt->error]);
}
$stmt->close();
$mysqli->close();

日期時間欄位對照表

MySQL 類型PHP 格式化範例
DATEdate('Y-m-d')2024-01-15
DATETIMEdate('Y-m-d H:i:s')2024-01-15 14:30:00
TIMESTAMPdate('Y-m-d H:i:s') 或 @timestamp1970-2038 年範圍
TIMEdate('H:i:s')14:30:00
YEARdate('Y')2024

錯誤碼設計規範

<?php
class ApiCode {
    public const SUCCESS       = 1000;
    public const DB_CONN_FAIL  = 1001;
    public const DB_EXEC_FAIL  = 1002;
    public const VALID_FAIL    = 1003;
    public const PARAM_MISSING = 1004;
    // ...
}

// 統一回應格式
function jsonResponse(int $code, string $message = '', mixed $data = null): never
{
    http_response_code($code >= 1000 ? 200 : 400); // 業務碼非 HTTP 碼
    echo json_encode([
        'code'    => $code,
        'message' => $message,
        'data'    => $data,
        'time'    => time(),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

遷移清單:從 mysql_* 到 PDO/MySQLi

  1. 全專案搜尋 mysql_(connect|query|fetch|escape)。
  2. 建立資料庫連接單例/連接池服務。
  3. 逐模組重寫:prepare() → bind_param/execute() → fetch()。
  4. 刪除所有 addslashes()、mysql_real_escape_string() 手動轉義。
  5. 啟用嚴格錯誤模式 (ERRMODE_EXCEPTION) 統一異常處理。
  6. 補全單元測試覆蓋資料庫操作邏輯。

核心鐵律:永遠使用參數化查詢,永不拼接 SQL 字串,時間格式務必匹配欄位類型。

copyright © 萬盛學電腦網 all rights reserved