1 回答
TA贡献1805条经验 获得超10个赞
您的代码容易受到 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...
}
}
- 1 回答
- 0 关注
- 100 浏览
添加回答
举报