我正在尝试根据某些属性(videos
,age
,year
)获得一些countries
。由于某些原因,即使我将参数正确绑定到查询并正确指定了查询(u.country NOT IN ($countries_count)
),我仍然可以获得country = U.S.A
的结果。我的bindParam
是否有用?请帮忙。
<?php
$parameters = json_decode(file_get_contents('php://input'), true);
$age = $parameters["age"];
$year = $parameters["year"];
$countries = sizeof($parameters["countries"]) == 0 ? array("0") : $parameters["countries"];
$countries_count = implode(",", array_fill(0, sizeof($countries), "?"));
$sql = "SELECT
v.title, u.name
FROM
video AS v JOIN user AS u ON v.id_user = u.id
WHERE
u.age <= ? AND YEAR(v.upload_date) >= ? AND
u.country NOT IN ($countries_count);";
$connection = new PDO("mysql:host=localhost;dbname=data_base", "root", "");
$statement = $connection->prepare($sql);
$statement->bindParam(1, $age, PDO::PARAM_INT);
$statement->bindParam(2, $year, PDO::PARAM_INT);
foreach ($countries as $k => $x) {
$statement->bindParam($k+3, $x, PDO::PARAM_STR);
}
$statement->execute();
echo json_encode($statement->fetchAll());
?>
答案 0 :(得分:1)
将bindParam更改为bindValue
如果要使用bindParam,请将sql更改为
u.age <= :age and
YEAR(v.upload_date) >= :year
...
然后绑定参数:
->bindParam(':age', $age)
->bindParam(':year', $year)
答案 1 :(得分:1)
您的问题是,您将所有IN
参数绑定到同一个变量($x
),因此它们最终都具有相同的值。您可以通过更改为bindValue
或绑定到实际的数组值(即
$statement->bindParam($k+3, $countries[$k], PDO::PARAM_STR);