首頁 > 後端開發 > php教程 > 如何在 MySQL INSERT 語句中安全地包含 PHP 變數?

如何在 MySQL INSERT 語句中安全地包含 PHP 變數?

Barbara Streisand
發布: 2024-12-21 18:03:23
原創
964 人瀏覽過

How to Safely Include PHP Variables in MySQL INSERT Statements?

在MySQL 語句中包含PHP 變數

在這種情況下,您在將值插入「內容」表時遇到問題,特別是在MySQL 語句的「VALUES」部分使用PHP 變數「$type」時。讓我們深入研究適當的方法。

1.使用準備好的語句(建議)

此方法可以解決 99% 的查詢,包括您的查詢。表示 SQL 資料文字(字串或數字)的任何變數都必須透過準備好的語句合併,沒有例外。然而,靜態值可以原樣插入。

準備過程需要四個階段:

  • 為 SQL 語句中的變數指定佔位符。
  • 準備修改後的查詢。
  • 將變數綁定到對應的佔位符。
  • 執行

以下是它在不同資料庫驅動程式中的工作方式:

mysqli 與PHP 8.2 :

$sql = "INSERT INTO contents (type, reporter, description) VALUES ('whatever', ?, ?)";
$mysqli->execute_query($sql, [$reporter, $description]);
登入後複製
mysqli 與PHP 8.2 :

$stmt = $mysqli->prepare("INSERT INTO contents (type, reporter, description) VALUES ('whatever', ?, ?)");
$stmt->bind_param("ss", $reporter, $description);
$stmt->execute();
登入後複製

mysqli與早期的PHP版本:

$sql = "INSERT INTO contents (type, reporter, description) VALUES ('whatever', ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$reporter, $description]);
登入後複製

PDO:

2。對查詢部分實施白名單過濾

$allowed = ["name", "price", "qty"];
$key = array_search($orderby, $allowed, true);
if ($key === false) { throw new InvalidArgumentException("Invalid field name"); }
登入後複製
如果您需要包含代表SQL 查詢特定部分的變量,例如關鍵字、表或欄位名稱或運算符,請使用「白名單」來確保其有效性。

例如,如果變數表示按欄位排序:
$allowed = ["ASC", "DESC"];
$key = array_search($direction, $allowed, true);
if ($key === false) { throw new InvalidArgumentException("Invalid ORDER BY direction"); }
登入後複製

同樣,檢查有效排序方向:
$query = "SELECT * FROM `table` ORDER BY `$orderby` $direction";
登入後複製
驗證後,準備查詢字串,並記住根據MySQL 語法正確轉義標識符:

以上是如何在 MySQL INSERT 語句中安全地包含 PHP 變數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板