简体   繁体   English

在MySQL中使用预处理语句是否可以防止SQL注入攻击?

[英]Does using prepared statements in MySQL prevent SQL injection attacks?

I'd just like to verify if using prepared statements in MySQL prevents SQL injection. 我只想验证在MySQL中使用预处理语句是否会阻止SQL注入。

Will the following code prevent all SQL injection attacks? 以下代码是否会阻止所有SQL注入攻击?

$var = $_GET['q']; 
$trimmed = trim($var);
if ($trimmed != NULL) {
  $get_fighters = $DBH->prepare(
    'SELECT * 
    FROM fighters 
    WHERE name LIKE :searchTerm 
      OR nickname LIKE :searchTerm 
      OR born_in_city LIKE :searchTerm
      OR born_in_state LIKE :searchTerm
      OR born_in_country LIKE :searchTerm
      ORDER BY name ASC');
  $get_fighters->bindValue(':searchTerm', '%' . $trimmed . '%', PDO::PARAM_STR);
  $get_fighters->setFetchMode(PDO::FETCH_ASSOC);
  $get_fighters->execute();
  $check_results_fighters = $get_fighters->rowCount();

  $get_events = $DBH->prepare(
    'SELECT * 
    FROM events 
    WHERE event_name LIKE :searchTerm
      OR event_arena LIKE :searchTerm
      OR event_city LIKE :searchTerm
      OR event_state LIKE :searchTerm
      OR event_country LIKE :searchTerm
      OR organization LIKE :searchTerm
    ORDER BY event_date DESC');

  $get_events->bindValue(':searchTerm', '%' . $trimmed . '%', PDO::PARAM_STR);
  $get_events->setFetchMode(PDO::FETCH_ASSOC);
  $get_events->execute();
  $check_results_events = $get_events->rowCount(); 
}

Prepared queries prevent attacks by separating the query to be ran, and the data to be used for that query. 准备好的查询通过分离要运行的查询以及要用于该查询的数据来防止攻击。 That means that a first-order attack cannot occur, since you're not concatenating data directly into the query. 这意味着不能发生一阶攻击,因为您没有直接将数据连接到查询中。

In short, if you always use prepared queries, and all of your data is sent with bound parameters (including data from other queries!) then you are fine, as far as SQL injection goes. 简而言之,如果您总是使用准备好的查询,并且所有数据都是使用绑定参数(包括来自其他查询的数据)发送的,那么就SQL注入而言,您没问题。

(I should also note that some PDO drivers for servers that do not support prepared queries will fake it with traditional escape routines. Don't concern yourself with this. It's safe.) (我还应该注意,一些不支持准备好的查询的服务器的PDO驱动程序会用传统的转义程序伪造它。不要担心这个。这很安全。)

Yes, using prepared statements will prevent SQL Injection according to the php documentation. 是的,根据php文档,使用预准备语句将阻止SQL注入。

See Link 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM