所以我正在构建一个用户选择多个位置的工作网站,它应该返回相应的工作。这意味着我将从用户那里获得一系列位置。我如何使用PDO绑定此数组。目前我只是将值直接添加到SQL中,但我知道这是一个安全问题。我怎么能重写它所以它使用如下语法:
$stmt->bindValue(":locations", $locations);
这是我所拥有的:
$location = $_POST['location'];
$locs = "'" . implode("', '", $location) . "'";
//create query
$sql =
"SELECT *
FROM job
JOIN location ON job.location_id = location.id
WHERE location.region IN ($locs)
";
//get results
try
{
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo $ex->getMessage();
}
//print results
foreach($results as $res)
{
echo "<p>Title:" . $res['title'];
echo "<p>Views:" . $res['views'];
echo "<p>Created At:" . $res['created_at'];
echo "<p>Image:" . $res['img_url'];
echo "<p>Salary:" . $res['salary'];
echo "<p>Region:" . $res['region'];
echo "<p>State:" . $res['state'];
echo "<br/><br/>";
}
答案 0 :(得分:1)
无法将数组绑定到IN
子句中使用的列表。但是,您可以绑定多个标量值,如下所示:
where location.region in (:region1, :region2, :region3, [...])
$params = array(
':region1' => $regions[0],
':region2' => $regions[1],
':region3' => $regions[2]
[...]
);
$stmt->execute($params);
您需要以编程方式构建查询的IN ($placeholders)
部分,以处理动态数量的参数。