如何在php中动态绑定参数?

我想做的是在 php 中构建一个搜索功能,以从 mysql 数据库中获取数据。


问题是查询是根据用户输入动态生成的。我在与搜索参数匹配的表单中有几个输入字段,例如,我可以搜索产品的名称或年份(分隔的输入表单),或者我可以只搜索名称或只搜索年份。


我成功构建了 SQL 查询,并且可以成功地为有效的 select 语句传递值。


但是我想用参数化查询来防止 SQL 注入。


这是我用来生成查询的代码片段:


$searchKeyword = $_POST['searchKeyWord'];

$year = $_POST['searchYear'];

$location = $_POST['searchLocation'];

$alcool = $_POST['alcol'];

$query = "SELECT * FROM CAPS WHERE 1";


if($searchKeyword != null) {

    $query.=" and name like '%$searchKeyword%' ";

}


if($year != null) {

    $query.="and year='$year' ";

}


if($location != null) {

    $query.="and location like '%$location%' ";

}


if($alcool != "none") {

    $query.=" and alcool='$alcool'";

}

它按原样构建查询,我只能有一个带输入的字段,它类似于


SELECT * 

FROM CAPS 

WHERE 1  

  AND name LIKE '%Cola%'` 

或者也可以


SELECT * 

FROM CAPS 

WHERE 1 

  AND name LIKE '%Cola%' 

  AND year = '1999' 

  AND location LIKE '%London%'

我的问题是:如果我将查询中的“$variable”替换为“?”,如何根据生成的查询插入输入?


慕勒3428872
浏览 74回答 1
1回答

holdtom

您的代码容易受到 SQL 注入的影响。由于您知道允许搜索的所有字段和操作,因此请使用白名单/*fieldname => operator*/$allowed = [    'alcool'   => 'like',    'location' => 'like',    'year'     => '=',    'name'     => 'like',];// fake input (one unknown field)$_POST['alcool']   = 'tee';$_POST['location'] = 'home';$_POST['password'] = 'hello';$fields     = [];$queryParts = [];$parameters = [];foreach($allowed as $field => $op) {    if (isset($_POST[ $field ])) {        $fields[] = $field;        $value = $_POST[ $field ];        if ($op == 'like') { // prepare string for LIKE '%...%'            $value = sprintf('%%%s%%', $value); // =>         }        $queryParts[] = sprintf('`%s` %s ?', $field, $op);        $parameters[] = $value;    }}$searchSql = sprintf('SELECT id, alcool, location, year, ... FROM table WHERE %s', implode(' AND ', $queryParts));echo $searchSql . PHP_EOL;print_r($parameters);输出 :SELECT id, alcool, location, year, ... FROM table WHERE `alcool` like ? AND `location` like ?Array(    [0] => %tee%    [1] => %home%)与 PDO(或您正在使用的任何驱动程序)一起使用$pdo = new PDO(...);$stmt = $pdo->prepare($searchSql);if ($stmt) {    $stmt->execute($parameters);    while($row = $stmt->fetch()) {        // your results...    }}
打开App,查看更多内容
随时随地看视频慕课网APP