準備語句與轉義:一種平衡行為
在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中文網其他相關文章!