在我的表格中
posts tags
[ id - title ] [pid - tag]
[ 1 - echo ] [ 1 - PHP]
[ 2 - for ] [ 1 - PDO]
[ 2 - PHP]
我做这个查询
if(isset($_POST['submit'])){
$tag = implode(",",$_POST['tags']);
$query = "
SELECT a.title FROM posts a
INNER JOIN tags b ON a.id = b.pid
WHERE b.tag IN (:tag)
";
$stmt = $pdo->prepare($query);
$stmt->execute(['tag' => $tag]);
while($row = $stmt->fetch()){
echo $row['title'];
}
}
以下是发生的事情
如果我只选择[PHP]
,我会得到结果[echo - for]
如果我只选择[PDO]
,我会得到结果[echo]
,
但是如果我选择[php and pdo]
我根本没有得到任何结果,我希望得到结果echo
。我该如何解决我的疑问?
答案 0 :(得分:1)
不幸的是,即使你现在认为它们已经覆盖了这个......不,你不能将数组绑定到准备好的语句。
最终您有2个选项,将其作为字符串直接提供给查询或使用FIND_IN_SET
$tags = implode(",",$_POST['tags']);
$inString = implode(',', array_fill(0, count($tags), '?'));
$query = $db->prepare('
SELECT a.title FROM posts a
INNER JOIN tags b ON a.id = b.pid
WHERE b.tag IN(' . $inString . ')'
);
foreach ($_POST['tags'] as $key => $tag){
$query->bindValue(($key+1), $tag);
}
$query->execute();
$tags = implode(",",$_POST['tags']);
$query = $db->prepare('
SELECT a.title FROM posts a
INNER JOIN tags b ON a.id = b.pid
WHERE FIND_IN_SET(b.tag, :array)'
);
$query->bindParam('array', $tags);
$query->execute();