准备语句和转义:一种平衡行为
在 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中文网其他相关文章!