PDO绑定使用bindParam()和IN()条件对字符串进行多次转换

时间:2018-03-19 23:09:23

标签: php mysql pdo bindparam

我遇到的麻烦是,当我尝试将绑定的变量传递给查询(存储在变量$searchString中)时,我没有得到任何响应。

变量$searchString = 'extreme', 'water'

我的PDO / MySQL声明:

$sql = "SELECT * 
        FROM posts 
            INNER JOIN post_tags ON posts.id = post_tags.postid 
            INNER JOIN tags ON post_tags.tagid = tags.id 
        WHERE tags.tag IN ( :searchTags ) 
        AND posts.suspended = 0 
        GROUP BY posts.id";

$results = $db->prepare($sql);
$results->bindParam(':searchTags', $searchString);
$results->execute();
while ($row = $results->fetch()) {
    echo $row[0]; // Should be the first column which is "id"
}

预期输出:1(在我的数据库中,只有一个项目与查询匹配,其ID为1)

我怀疑bindParam()函数与$searchString的值混淆,好像我删除了bindParam()行并将变量直接放入它运行的SQL查询中,如下所示:

$sql = "SELECT * FROM posts INNER JOIN post_tags ON posts.id = post_tags.postid INNER JOIN tags ON post_tags.tagid = tags.id WHERE tags.tag IN ({$searchString}) AND posts.suspended = 0 GROUP BY posts.id";

注意:变量$searchString必须有单引号'才能使SQL查询生效

0 个答案:

没有答案