我的数据库如下所示:
我有一个看起来像这样的变量:
$following = "John, Sarah";
我想获取列'用户名'在变量$following
中(在这种情况下,John和Sarah)。为此,我查看了答案https://stackoverflow.com/a/1356018/5798798,建议我在我的查询中使用IN
,我尝试过:
$following = "John, Sarah";
$stmt = $con->prepare("SELECT * FROM events WHERE username IN ('$following')");
$stmt->execute();
while($row = $stmt->fetch()) {
echo $row['eventtype'];
}
问题是查询没有返回任何数据。我想要的结果是:
说话走了
答案 0 :(得分:2)
From what I suggested in comments to use the following:
$following = "John, Sarah";
$following = explode(", ", $following);
$string = implode(", ", $following);
It ended up that I didn't include the quotes for the implode()
'ing.
The final solution was to add the single quotes in the first parameter for the implode()
function:
$following = implode("','",$following);
答案 1 :(得分:1)
$following = join("', '", $following);
join
不再返回数组。现在是一个字符串。
您可以使用Static class variables in Python:
$in = str_repeat('?,', count($following ) - 1) . '?';
$stmt = $con->prepare("SELECT * FROM events WHERE username IN ($in)");
$stm->execute($following);
答案 2 :(得分:-2)
没有使用join你可以通过以下方式直接内爆数组
$stmt = $con->prepare('SELECT * FROM events WHERE username IN ("'. implode('","', $following).'")');
$stmt->execute();
while($row = $stmt->fetch()) {
echo $row['eventtype'];
}
注意:$ follow总是应该在数组
中