首頁 >資料庫 >mysql教程 >準備好的語句是否消除了 PHP 中對 mysql_real_escape_string() 的需要?

準備好的語句是否消除了 PHP 中對 mysql_real_escape_string() 的需要?

Linda Hamilton
Linda Hamilton原創
2024-11-04 11:34:01601瀏覽

Do Prepared Statements Eliminate the Need for `mysql_real_escape_string()` in PHP?

準備語句與轉義:一種平衡行為

在PHP 中使用準備語句時,是否還需要使用mysql_real_escape_string() 來防止SQL注入?讓我們檢查一個特定的查詢及其實作來回答這個問題。

查詢和實現

<code class="php">$consulta = $_REQUEST["term"] . "%";

$sql = $db->prepare('select location from location_job where location like ?');

$sql->bind_param('s', $consulta);
$sql->execute();
$sql->bind_result($location);

$data = array();

while ($sql->fetch()) {
    $data[] = array('label' => $location);
}
?>

**The Dilemma**

The provided query aims to fetch locations that match the term entered in the $_REQUEST["term"] variable. While the usage of a prepared statement is commendable for preventing SQL injections, the implementation raises a query: is mysql_real_escape_string() still necessary in this case?

**The Verdict: No, but a Refinement is Suggested**

When using prepared statements, as long as they are employed correctly, they effectively shield against SQL injections. In this instance, mysql_real_escape_string() is redundant. However, a minor improvement can enhance the code's clarity and efficiency.

Rather than using bind_param('s', $consulta), it's more straightforward to pass parameters through the execute method, especially when utilizing the '?' placeholder. The updated code would be:
</code>

$sql->execute([$consulta]);

為什麼重要

帶有參數綁定的準備好的語句確保外部資料無法操作SQL 查詢。但是,請記住,僅 SQL 參數綁定並不能保證 HTML 中的安全性顯示。為此,在輸出查詢結果之前使用 htmlspecialchars() 等函數至關重要。

以上是準備好的語句是否消除了 PHP 中對 mysql_real_escape_string() 的需要?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn