保护动态where子句(PDO)

时间:2018-07-09 12:52:22

标签: php mysql pdo

在我的表单中,我有一个选择和一个输入,就像这样:

<div class="row">
  <div class="col-md-4">
    <select id="select-column" name="column" class="form-control">
      <option value="bin_id">Bin ID</option>
      <option value="table_col_one">Column One</option>
      <option value="table_col_two">Column Two</option>
      <option value="table_col_three">Column Three</option>
    </select>
  </div>

  <div class="col-md-8">
    <div>
      <input id="search" name="term" type="text" class="form-control">
    </div>
  </div>
</div>

用户选择要搜索的列,这是我的SQL查询:

$term = $_POST['term'];
$column = $_POST['column'];

$sql = "SELECT $column FROM packing_master WHERE $column LIKE :term AND invoice != '' group by $column LIMIT 35";
$stmt = $bdd->prepare($sql);
$stmt->bindParam(':term', $term);
$stmt->execute();

但是如何保护请求?因为它容易受到sql注入的攻击?

2 个答案:

答案 0 :(得分:3)

white list允许的列名称一起使用:

$term = $_POST['term'];
$column = $_POST['column'];

$allowed_columns = ['col1', 'col2', 'col3']; 
// or query a database to get columns in the table you're operating on

if (!in_array($column, $allowed_columns)) {
    // throw exception or do anything else that prevents further query execution
}

答案 1 :(得分:0)

好吧,基本上,参数绑定对于保护Web应用程序免受SQL注入至关重要。几乎所有将在SQL语句中使用的数据都需要绑定。简而言之,绑定只是一种告诉引擎特定数据是字符串,数字,字符等的方式。通过这样做,引号和双引号,分号等特殊字符将不会被数据库解释为命令。

示例:

public function dbSelect($table, $fieldname=null, $id=null) {
    $this->conn();
    $sql = "SELECT * FROM `$table` WHERE `$fieldname`=:id";
    $stmt = $this->db->prepare($sql);
    $stmt->bindParam(':id', $id);
    $stmt->execute();

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}