萬盛學電腦網

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

MySQL 查詢與 mysql_num_rows 記錄數檢查:安全防注入與資源釋放最佳實務

原始程式碼問題分析

<?php
function getCityId($cd) {
    $sql = "Select id,cntitle from zgy_classplace where cntitle='$cd'";
    $result = mysql_query($sql) or die(mysql_error());
    if (mysql_num_rows($result)) {
        $rs = mysql_fetch_array($result);
        return $rs['id'];
    } else {
        return 1; // 預設值
    }
    mysql_free_result($result); // 永遠不會執行!
}
?>

三大缺陷:

  1. SQL 注入風險: 直接插值 $cd 未轉義。
  2. 資源洩漏: return 之後的 mysql_free_result() 永不執行。
  3. 使用已棄用 API: mysql_* 函數 PHP 7.0+ 已移除。

修正版:MySQLi 預處理語句

<?php
function getCityId(mysqli $mysqli, string $cd): int {
    $sql = "SELECT id FROM zgy_classplace WHERE cntitle = ? LIMIT 1";
    $stmt = $mysqli->prepare($sql);
    if (!$stmt) {
        error_log("Prepare failed: " . $mysqli->error);
        return 1;
    }
    
    $stmt->bind_param('s', $cd);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        $id = (int)$row['id'];
    } else {
        $id = 1; // 不存在時預設
    }
    
    $result->free();
    $stmt->close();
    return $id;
}
?>

PDO 版本 (推薦新專案)

<?php
function getCityId(PDO $pdo, string $cd): int {
    $sql = "SELECT id FROM zgy_classplace WHERE cntitle = ? LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$cd]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ? (int)$row['id'] : 1;
    // PDOStatement 自動在銷毀時釋放資源
}
?>

關鍵最佳實務總結

議題錯誤做法正確做法
參數綁定字串插值 "... WHERE col='$var'"預處理 ? / :name + bind_param/execute([])
資源釋放return 後釋放try/finally、defer 模式、或 PDO 自動管理
錯誤處理or die() 直接終止記錄日誌、拋出例外、回傳錯誤代碼
預設值語意硬編碼 return 1拋出 NotFoundException 或回傳 null/false

效能優化提示

  • 加上 LIMIT 1 避免全表掃描 (已有唯一索引更佳)。
  • 確認 cntitle 欄位有索引:ALTER TABLE zgy_classplace ADD INDEX idx_cntitle (cntitle)。
  • 高頻查詢考慮 Redis 快取:city:{name} → id,TTL 1 小時。
copyright © 萬盛學電腦網 all rights reserved