PDO bindParam无法在IN绑定中进行SQL查询

时间:2019-05-28 01:51:21

标签: php

我正在尝试根据某些属性(videosageyear)获得一些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());
?>

2 个答案:

答案 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);